none
.net core 2.0使用不带ASP.NET Core Identity的cookie身份验证问题 RRS feed

  • 问题

  • HttpContext.User.Identity中一直无法写入认证信息,我的代码如下:

      //用户信息
                var claims = new[]
                    {
                        new Claim(ClaimTypes.Name, "test")
                     };
    
                var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
    
                ClaimsPrincipal user = new ClaimsPrincipal(claimsIdentity);
    
                //登录用户,相当于ASP.NET中的FormsAuthentication.SetAuthCookie
                HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, user);

    Startup.cs配置如下:

    public class Startup
        {
            public Startup(IConfiguration configuration)
            {
                Configuration = configuration;
            }
    
            public IConfiguration Configuration { get; }
    
            // This method gets called by the runtime. Use this method to add services to the container.
            public void ConfigureServices(IServiceCollection services)
            {
                services.AddMvc();
                //注册Cookie认证服务
                services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie();
            }
    
            // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
            public void Configure(IApplicationBuilder app, IHostingEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseBrowserLink();
                    app.UseDeveloperExceptionPage();
                }
                else
                {
                    app.UseExceptionHandler("/Home/Error");
                }
    
                app.UseStaticFiles();
    
                app.UseAuthentication();
    
                app.UseMvc(routes =>
                {
                    routes.MapRoute(
                        name: "default",
                        template: "{controller=Home}/{action=Index}/{id?}");
                });
            }
        }

    我不知道是否我的配置问题还是UseAuthentication中间件的问题。一直无法写入到cookie中。



    2018年4月28日 11:15

全部回复

  • 你好,

    根据你的代码,我发现你没有使用list<claim>而使用了claim的数组。

    据我所知如果是数组的话,这些claim并不会添加到cookie里面去。

    我建议你使用List<claim>

    具体你可以参照如下代码:

            public  void OnPost()
            {
    
    
                var claims = new List<Claim>
            {
        new Claim(ClaimTypes.Name, "aaaa.com"),
        new Claim("FullName", "aaaaa"),
        new Claim(ClaimTypes.Role, "Administrator"),
           };
    
                var claimsIdentity = new ClaimsIdentity(
                    claims, CookieAuthenticationDefaults.AuthenticationScheme);
    
                var authProperties = new AuthenticationProperties
                {
                    //AllowRefresh = <bool>,
                    // Refreshing the authentication session should be allowed.
    
                    //ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(10),
                    // The time at which the authentication ticket expires. A 
                    // value set here overrides the ExpireTimeSpan option of 
                    // CookieAuthenticationOptions set with AddCookie.
    
                    //IsPersistent = true,
                    // Whether the authentication session is persisted across 
                    // multiple requests. Required when setting the 
                    // ExpireTimeSpan option of CookieAuthenticationOptions 
                    // set with AddCookie. Also required when setting 
                    // ExpiresUtc.
    
                    //IssuedUtc = <DateTimeOffset>,
                    // The time at which the authentication ticket was issued.
    
                    //RedirectUri = <string>
                    // The full path or absolute URI to be used as an http 
                    // redirect response value.
                };
    
                  HttpContext.SignInAsync(
                    CookieAuthenticationDefaults.AuthenticationScheme,
                    new ClaimsPrincipal(claimsIdentity),
                    authProperties);
        
            }

    结果:


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    2018年4月30日 6:41
  • 感谢你的回答。我现在使用的就是list<claim>

    还有是有这个问题,有时候无法写,有时候又能正常使用。我不知道是我运行环境的问题还是UseAuthentication中间件本身的问题。同样的代码一样的环境不同结果。。。。。。

    这是我当时的运行效果git图:

    • 已编辑 K..0 2018年5月7日 2:35
    2018年5月7日 2:21
  • 你好,

    你所说的无法写,是什么情况。

    有没有详细的错误信息?

    我建议你能够贴一下未写成功的情况,以及如何重现你的问题。

    如果你可以给更多的信息,这样方便我重现你的问题并且发现解决方案。


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    2018年5月8日 6:14