只有当用户更改密码或取消与外部登录的链接时,才会创建新的安全戳。
默认情况下,Cookie的验证时间间隔为30分钟。由于您使用的是最新的.net核心版本,因此可以在
ConfigureServices()
startup.cs
以延长验证时间。
如果时间设置为0,它将在每个请求中验证
services.Configure<SecurityStampValidatorOptions>(options =>
{
// This is the key to control how often validation takes place
options.ValidationInterval = TimeSpan.FromMinutes(30);
});
注意
userManager.UpdateSecurityStampAsync(user)
. 如果您在登录后使用这个,验证很可能会失败。
最后,如果您想用自己的方式处理这个行为,您可以编写自己的验证器并在中间件中连接
services.AddAuthentication(options =>
{
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
}).AddCookie(options =>
{
options.Events.OnValidatePrincipal = LastChangedValidator.ValidateAsync;
});
public static class LastChangedValidator
{
public static async Task ValidateAsync(CookieValidatePrincipalContext context)
{
// you can use your own logic
/* var userRepository = context.HttpContext.RequestServices.GetRequiredService<IUserRepository>();
var userPrincipal = context.Principal;
// Look for the last changed claim.
string lastChanged;
lastChanged = (from c in userPrincipal.Claims
where c.Type == "LastUpdated"
select c.Value).FirstOrDefault();
if (string.IsNullOrEmpty(lastChanged) ||
!userRepository.ValidateLastChanged(userPrincipal, lastChanged))
{
context.RejectPrincipal();
await context.HttpContext.Authentication.SignOutAsync("MyCookieMiddlewareInstance");
} */
}
}
否则你可以处理
ValidatePrincipal()
public class CustomCookieHandler: CookieAuthenticationEvents
{
public override Task ValidatePrincipal(CookieValidatePrincipalContext context)
{
return base.ValidatePrincipal(context);
}
}