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

Blu*_*ght 6 c# cookies asp.net-mvc asp.net-core asp.net-core-2.0

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

Startup.cs(配置服务)

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

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

Startup.cs(配置)

app.UseAuthentication();
Run Code Online (Sandbox Code Playgroud)

账户控制器.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
});
Run Code Online (Sandbox Code Playgroud)

不幸的是,我的 .NET Cookie 从未设置过。这意味着 User.Identity.IsAuthenticated 始终为 false。我尝试了许多 cookie 选项,例如将 Cookie.SameSite 或 Cookie.SecurePolicy 更改为所有可能的值。

我使用 Visual Studio 2017、本地主机通过 https、Chrome 61。

Oct*_*scu 3

假设您正在为您的应用程序提供服务, Chrome 浏览器localhost似乎不会为 IP 或 Intranet 主机名(例如. 您可以从 IIS 为您的应用程序提供服务并使用具有有效主机名的绑定。localhost