简体   繁体   English

未设置 ASP.NET Core 2.0 身份验证 Cookie

[英]ASP.NET Core 2.0 Authentication Cookie not set

I followed this article ( https://docs.microsoft.com/en-us/aspnet/core/security/authentication/cookie?tabs=aspnetcore2x ) of Microsoft to migrate my Authentication Procedure in my .NET Core 2.0 MVC Application.我按照 Microsoft 的这篇文章 ( https://docs.microsoft.com/en-us/aspnet/core/security/authentication/cookie?tabs=aspnetcore2x ) 在我的 .NET Core 2.0 MVC 应用程序中迁移了我的身份验证程序。

Startup.cs (ConfigureServices) Startup.cs(配置服务)

services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

services.AddAuthentication("MyCookieAuthenticationScheme")
        .AddCookie("MyCookieAuthenticationScheme", options => {
            options.AccessDeniedPath = "/Account/Forbidden/";
            options.LoginPath = "/Account/Login/";
        });

Startup.cs (Configure) Startup.cs(配置)

app.UseAuthentication();

AccountController.cs账户控制器.cs

List<Claim> claims = new List<Claim> {
                        new Claim(ClaimTypes.Name, "testUser"),
                        new Claim(ClaimTypes.Email, model.Email),
                        //new Claim("ID", user.ID.ToString(), ClaimValueTypes.Integer),
                        new Claim(ClaimTypes.Role, "Admin")
                    };

ClaimsIdentity identity = new ClaimsIdentity(claims, "MyCookieAuthenticationScheme");

ClaimsPrincipal principal = new ClaimsPrincipal(identity);

await HttpContext.SignInAsync("MyCookieAuthenticationScheme", principal, new AuthenticationProperties
{
    IsPersistent = false
});

Unfortunately my .NET Cookie is never set.不幸的是,我的 .NET Cookie 从未设置过。 That means User.Identity.IsAuthenticated is always false.这意味着 User.Identity.IsAuthenticated 始终为 false。 I tried many cookie options like changing Cookie.SameSite or Cookie.SecurePolicy to all possible values.我尝试了许多 cookie 选项,例如将 Cookie.SameSite 或 Cookie.SecurePolicy 更改为所有可能的值。

I work with Visual Studio 2017, localhost over https, Chrome 61.我使用 Visual Studio 2017、本地主机通过 https、Chrome 61。

Assuming that you are serving your application on localhost , it seems that the Chrome browser does not set the cookies for IPs or intranet hostnames like localhost .假设您在localhost上为您的应用程序提供服务, Chrome 浏览器似乎没有为 IP 或内部网主机名(如localhost设置 cookie。 You can serve your application from IIS and use a binding with a valid host name.您可以从 IIS 为您的应用程序提供服务,并使用具有有效主机名的绑定。

I think you should provide login process using by Identity's UserManager class instead of HttpContext.SignInAsync.我认为您应该提供使用 Identity 的 UserManager 类而不是 HttpContext.SignInAsync 的登录过程。 Inject IUserManager to your controller constructor, and use it to login.将 IUserManager 注入您的控制器构造函数,并使用它登录。

AccountController: Controller
{
    private readonly SignInManager<ApplicationUser> _signInManager;

    public AccountController(SignInManager<ApplicationUser> singInManager)
    {
        _signInManager = signInManager;
    }

    public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
    {
        var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
        ...
    }

}

You can modify Identity's cookie settings in your Startup.cs.您可以在 Startup.cs 中修改 Identity 的 cookie 设置。 Take a glance:看一眼:

https://docs.microsoft.com/en-us/aspnet/core/security/authentication/identity https://docs.microsoft.com/en-us/aspnet/core/security/authentication/identity

When upgrading our site's authentication system for .NET Core 2.0, I had to update our controller method to use the AuthenticationHttpContextExtensions.SignInAsync() method instead of the old HttpContext.SignInAsync() .在为 .NET Core 2.0 升级我们站点的身份验证系统时,我必须更新我们的控制器方法以使用AuthenticationHttpContextExtensions.SignInAsync()方法而不是旧的HttpContext.SignInAsync()

Example:示例:

public async Task ClaimsLogin() {

    // Claims identity creation here...

    ClaimsPrincipal principal = new ClaimsPrincipal(identity);

    await Task.FromResult(
        AuthenticationHttpContextExtensions.SignInAsync(
            this.httpContextAccessor.HttpContext,
            "NameOfYourCookieHere",
            userPrincipal,
            new AuthenticationProperties()
            {
                ExpiresUtc = DateTime.UtcNow.AddMinutes(2880),
                IsPersistent = false,
                AllowRefresh = false
            }));
}

Hopefully this helps someone!希望这对某人有所帮助!

I was getting the same issue, after trying lot of googling and stackoverflow answers for hours I couldn't log in despite getting success from the SignInManager.我遇到了同样的问题,在尝试了数小时的大量谷歌搜索和 stackoverflow 答案后,尽管从 SignInManager 获得了成功,但我还是无法登录。 So what I did solve the problem is added .AspNetCore.Identity.Application in cookie Name manually, and added a random token in the value field then I was able to log in sucessfully.所以我所做的解决问题是手动在cookie Name中添加.AspNetCore.Identity.Application,并在值字段中添加一个随机令牌然后我就可以成功登录了。 Again after logging out the identity token was gone from the cookie but after login in again it came in the cookie this time.再次注销后,身份令牌从 cookie 中消失了,但这次再次登录后,它又出现在了 cookie 中。

I hope this process helps some one who has gone through like me.我希望这个过程可以帮助像我一样经历过的人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM