我正在尝试在我的.net核心MVC项目中使用Cookie身份验证 . 这个过程是在注册后我在ASPNetUsers表中有一个条目,我已经扩展了这个表以包含userType . 用户登录后,我可以通过Chrome浏览器看到cookies集合中有cookie . 当我尝试在登录后重定向用户时失败 . 如果我装饰我用 [AllowAnonymous]
重定向的方法,方法会被击中,所以我知道重定向是正确的 .
在我的控制器的顶部我有 [Authorize(ActiveAuthenticationSchemes = "Cookie")]
当我启动应用程序时,我使用以下代码注册Identity:
services.AddIdentity<ApplicationUser, IdentityRole<int>>(
config => { config.User.RequireUniqueEmail = true;
config.Cookies.ApplicationCookie.LoginPath = "/Account/Login";
config.Cookies.ApplicationCookie.Events = new CookieAuthenticationEvents()
{
OnRedirectToLogin = async ctx =>
{
if (ctx.Request.Path.StartsWithSegments("/visualjobs") && ctx.Response.StatusCode == 200)
{
ctx.Response.StatusCode = 401;
}
else
{
ctx.Response.Redirect(ctx.RedirectUri);
}
await Task.Yield();
}
};
}).AddEntityFrameworkStores<VisualJobsDbContext, int>()
.AddDefaultTokenProviders();
在启动配置中我有:
app.UseIdentity();
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AuthenticationScheme = "Cookie",
// LoginPath = new PathString("/Account/Login/"),
AutomaticAuthenticate = false
});
我错过了什么?
1 回答
在
AddIdentity
的调用中添加 AuthenticationScheme 和 AutomaticAuthenticate 选项,如下例所示:否则为时已晚,因为UseIdentity将在没有更新设置的情况下在
Cookies.ApplicationCookie
内部调用Cookies.ApplicationCookie
.