首页 > 解决方案 > 即使我重新启动程序,ASP.NET CORE 3.1 Cookie 也始终有效

问题描述

await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationSchema, principal);
//...

//Then 

HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationSchema);
return Redirect ……

我看到它让cookie立即过期。在响应标头中使用 set-cookie : XXXX 1970 XXXX。但是当我通过 chrome f12 应用程序 cookie 添加 cookie 时,我发现它仍然可以工作。即使我重新启动程序,

this.context.HttpContext.User.Identity.IsAuthenticated 

是真的。饼干仍然有效...

标签: c#asp.net-core

解决方案


如果 cookie 在浏览器会话中持续存在。只有当用户明确同意并在登录时选中“记住我”复选框或类似机制时,才能启用这种持久性。就像这个代码示例:

// using Microsoft.AspNetCore.Authentication;

await HttpContext.SignInAsync(
    CookieAuthenticationDefaults.AuthenticationScheme,
    new ClaimsPrincipal(claimsIdentity),
    new AuthenticationProperties
    {
        IsPersistent = true
    });

此代码片段创建了一个身份和相应的 cookie,它们在浏览器关闭后仍然存在。任何先前配置的滑动到期设置都将受到尊重。如果cookie在浏览器关闭时过期,浏览器会在重启后清除cookie。https://docs.microsoft.com/en-us/aspnet/core/security/authentication/cookie?view=aspnetcore-5.0


推荐阅读