Cookie中间件未正确设置Cookie

时间:2016-10-29 19:57:43

标签: c# authentication asp.net-core asp.net-core-mvc

我尝试使用ASP.NET Core中的Cookie中间件来创建自定义授权,如官方asp.net文档(https://docs.asp.net/en/latest/security/authentication/cookie.html)中所述。

不幸的是,它在我的ASP.NET MVC项目中没有工作,在调用“HttpContext.Authentication.SignInAsync”后没有设置cookie。

这是我目前的代码:

Startup.cs

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
            app.UseBrowserLink();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseStaticFiles();

        app.UseIdentity();

        app.UseCookieAuthentication(new CookieAuthenticationOptions()
        {
            AuthenticationScheme = "CookieInstance",
            LoginPath = new PathString("/Account/Login/"),
            AccessDeniedPath = new PathString("/Account/Forbidden/"),
            AutomaticAuthenticate = true,
            AutomaticChallenge = true,
            CookieSecure = env.IsDevelopment()
                ? CookieSecurePolicy.None
                : CookieSecurePolicy.Always                
        });            

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }

登录控制器

    [HttpPost]
    [AllowAnonymous]
    public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
    {
        if (ModelState.IsValid && model.Email == "test@test.com")
        {

            var claims = new List<Claim> {
                new Claim(ClaimTypes.Name, "Kev", ClaimValueTypes.String)
            };

            var userIdentity = new ClaimsIdentity(claims, "CookieInstance");

            var userPrincipal = new ClaimsPrincipal(userIdentity);

            await HttpContext.Authentication.SignInAsync("CookieInstance", userPrincipal,
                new AuthenticationProperties
                {
                    ExpiresUtc = DateTime.UtcNow.AddMinutes(20),
                    IsPersistent = false,
                    AllowRefresh = false
                });                    

            return RedirectToLocal(returnUrl);
        } else { ... }

    ...
    }

它成功地将我重定向到正确的页面,但显然没有设置cookie。例如,SignInManager.IsSignedIn(User)仍然返回false。

有没有人有解决方案?

感谢

1 个答案:

答案 0 :(得分:1)

如果您尝试使用ASP.NET标识SignInManager,即

SignInManager.IsSignedIn(User) 

该方法未使用您定义的相同身份验证方案,它使用默认IdentityOptions中的authscheme,因此它会报告为false,它将看不到您的身份验证Cookie。

该方法的实际代码如下:

    public virtual bool IsSignedIn(ClaimsPrincipal principal)
    {
        if (principal == null)
        {
            throw new ArgumentNullException(nameof(principal));
        }
        return principal?.Identities != null &&
            principal.Identities.Any(i => i.AuthenticationType == Options.Cookies.ApplicationCookieAuthenticationScheme);
    }

所以你可以用自己的身份验证方案进行类似的检查

请注意,该代码中的选项是IdentityOptions,Cookies属性是IdentityAuthOptions for Identity