我按照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 (Configure)
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始终为false . 我尝试了很多cookie选项,比如将Cookie.SameSite或Cookie.SecurePolicy更改为所有可能的值 .
我使用Visual Studio 2017,localhost over https,Chrome 61 .
3 回答
我认为您应该使用Identity的UserManager类而不是HttpContext.SignInAsync来提供登录过程 . 将IUserManager注入控制器构造函数,并使用它进行登录 .
您可以在Startup.cs中修改Identity的cookie设置 . 一瞥:
https://docs.microsoft.com/en-us/aspnet/core/security/authentication/identity
升级我们站点的.NET Core 2.0身份验证系统时,我不得不更新我们的控制器方法以使用
AuthenticationHttpContextExtensions.SignInAsync()
方法而不是旧的HttpContext.SignInAsync()
.例:
希望这有助于某人!
假设您在
localhost
上为您的应用程序提供服务,似乎Chrome browser没有为IP或Intranet主机名设置cookie,如localhost
. 您可以从IIS提供应用程序,并使用具有有效主机名的绑定 .