【发布时间】:2018-03-30 00:50:35
【问题描述】:
我按照 Microsoft 的这篇文章 (https://docs.microsoft.com/en-us/aspnet/core/security/authentication/cookie?tabs=aspnetcore2x) 在我的 .NET Core 2.0 MVC 应用程序中迁移了我的身份验证过程。
Startup.cs (ConfigureServices)
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddAuthentication("MyCookieAuthenticationScheme")
.AddCookie("MyCookieAuthenticationScheme", options => {
options.AccessDeniedPath = "/Account/Forbidden/";
options.LoginPath = "/Account/Login/";
});
Startup.cs(配置)
app.UseAuthentication();
AccountController.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
});
不幸的是,我的 .NET Cookie 从未设置。这意味着 User.Identity.IsAuthenticated 始终为假。我尝试了许多 cookie 选项,例如将 Cookie.SameSite 或 Cookie.SecurePolicy 更改为所有可能的值。
我使用 Visual Studio 2017、localhost over https、Chrome 61。
【问题讨论】:
-
您是否真的检查过是否没有设置 cookie 或者您只是在假设因为您无法进行身份验证?检查浏览器开发者控制台的 cookie,因为我很确定这段代码会设置 cookie。
-
呃,你是对的。我刚刚检查了控制台并生成了它。你知道为什么不会设置身份吗?
-
您能否删除 AddIdentity(...) 并在身份验证期间为其提供一些固定值以查看问题是否出在身份上,因为此代码非常简单并且可以正常工作。跨度>
-
如果我删除它,它会在调用其中包含 UserManager 的任何视图时立即失败:InvalidOperationException: No service for type 'Microsoft.AspNetCore.Identity.UserManager`1[PTCConnector.Models.ApplicationUser] ' 已注册。
-
@Rob 我的解决方案现在可以工作了:诀窍是您的所有组件都需要引用相同的身份 ID。所以我需要在 AddAuthentication..的选项中将 DefaultChallengeScheme、DefaultAuthenticateScheme 和 DefaultScheme 设置为 MyCookieAuthenticationScheme。
标签: c# asp.net-mvc cookies asp.net-core asp.net-core-2.0