在实现持久化 cookie 认证时,有几个需要注意的事项。
在 Startup.cs 中配置滑动过期时间。如果您明确设置所需的值并不使用默认设置,则会更清晰。
private void ConfigureAuthentication(IServiceCollection services)
{
services
.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.SlidingExpiration = true;
options.ExpireTimeSpan = TimeSpan.FromMinutes(20);
});
}
当用户勾选“记住我”标志后,配置 cookie 以在浏览器会话间持久化,并设置绝对过期时间(长短由您决定)。此设置将覆盖 SlidingExpiration 和 ExpireTimeSpan。在登录操作中:
List<Claim> claims = new List<Claim>();
var userIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
ClaimsPrincipal principal = new ClaimsPrincipal(userIdentity);
AuthenticationProperties authenticationProperties = new AuthenticationProperties() { IsPersistent = model.RememberMe };
if (model.RememberMe)
{
authenticationProperties.ExpiresUtc = DateTimeOffset.UtcNow.AddMonths(1);
}
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, authenticationProperties);
配置数据保护。在旧的经典asp.net webforms中记住machineKey。否则,每次IIS应用程序池重启后cookie将被重置。您应该在Startup.cs中进行身份验证之前配置数据保护。要将密钥存储在应用程序的根文件夹中:
private void ConfigureDataProtection(IServiceCollection services, IWebHostEnvironment environment)
{
var keysDirectoryName = "Keys";
var keysDirectoryPath = Path.Combine(environment.ContentRootPath, keysDirectoryName);
if (!Directory.Exists(keysDirectoryPath))
{
Directory.CreateDirectory(keysDirectoryPath);
}
services.AddDataProtection()
.PersistKeysToFileSystem(new DirectoryInfo(keysDirectoryPath))
.SetApplicationName("YourApplicationName");
}
来自文档: