Cookie中间件没有正确设置Cookie
本文关键字:Cookie 设置 中间件 | 更新日期: 2023-09-27 18:15:34
我尝试使用Cookie中间件从ASP。在asp.net官方文档(https://docs.asp.net/en/latest/security/authentication/cookie.html)中提到的创建自定义授权。
不幸的是,它不工作在我的ASP。. NET MVC项目中,调用"HttpContext.Authentication.SignInAsync"后没有设置cookie。
下面是我当前的代码:
Startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseIdentity();
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AuthenticationScheme = "CookieInstance",
LoginPath = new PathString("/Account/Login/"),
AccessDeniedPath = new PathString("/Account/Forbidden/"),
AutomaticAuthenticate = true,
AutomaticChallenge = true,
CookieSecure = env.IsDevelopment()
? CookieSecurePolicy.None
: CookieSecurePolicy.Always
});
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
<<p> 登录控制器/strong> [HttpPost]
[AllowAnonymous]
public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
{
if (ModelState.IsValid && model.Email == "test@test.com")
{
var claims = new List<Claim> {
new Claim(ClaimTypes.Name, "Kev", ClaimValueTypes.String)
};
var userIdentity = new ClaimsIdentity(claims, "CookieInstance");
var userPrincipal = new ClaimsPrincipal(userIdentity);
await HttpContext.Authentication.SignInAsync("CookieInstance", userPrincipal,
new AuthenticationProperties
{
ExpiresUtc = DateTime.UtcNow.AddMinutes(20),
IsPersistent = false,
AllowRefresh = false
});
return RedirectToLocal(returnUrl);
} else { ... }
...
}
它成功地将我重定向到正确的页面,但显然没有设置cookie。例如signinmanager . issigndin (User)仍然返回false。
有人有解决办法吗?
谢谢
如果您正在尝试使用ASP。. NET Identity SignInManager ie
SignInManager.IsSignedIn(User)
该方法没有使用您定义的相同身份验证方案,它使用默认IdentityOptions中的身份验证方案,因此它将报告false,它将看不到您的身份验证cookie。
该方法的实际代码如下:
public virtual bool IsSignedIn(ClaimsPrincipal principal)
{
if (principal == null)
{
throw new ArgumentNullException(nameof(principal));
}
return principal?.Identities != null &&
principal.Identities.Any(i => i.AuthenticationType == Options.Cookies.ApplicationCookieAuthenticationScheme);
}
所以你可以用你自己的验证方案
做类似的检查请注意,该代码中的Options是IdentityOptions, Cookies属性是Identity的CookieAuthOptions