身份验证的 Cookies 名称为 AspNetCore.Identity.Application
,其 ExpireTimeSpan
由 HandleSignInAsync 设置。
DateTimeOffset issuedUtc;
if (signInContext.Properties.IssuedUtc.HasValue)
{
issuedUtc = signInContext.Properties.IssuedUtc.Value;
}
else
{
issuedUtc = Clock.UtcNow;
signInContext.Properties.IssuedUtc = issuedUtc;
}
if (!signInContext.Properties.ExpiresUtc.HasValue)
{
signInContext.Properties.ExpiresUtc = issuedUtc.Add(Options.ExpireTimeSpan);
}
await Events.SigningIn(signInContext);
if (signInContext.Properties.IsPersistent)
{
var expiresUtc = signInContext.Properties.ExpiresUtc ?? issuedUtc.Add(Options.ExpireTimeSpan);
signInContext.CookieOptions.Expires = expiresUtc.ToUniversalTime();
}
您可以通过重写
HandleSignInAsync
实现自己的
CookieAuthenticationHandler
。
public class CustomCookieAuthenticationHandler : CookieAuthenticationHandler
{
public CustomCookieAuthenticationHandler(IOptionsMonitor<CookieAuthenticationOptions> options
, ILoggerFactory logger
, UrlEncoder encoder
, ISystemClock clock) : base(options, logger, encoder, clock)
{
}
protected override Task HandleSignInAsync(ClaimsPrincipal user, AuthenticationProperties properties)
{
if (user.Identity.Name == "test@outlook.com")
{
properties.ExpiresUtc = Clock.UtcNow.AddMinutes(15);
}
else
{
properties.ExpiresUtc = Clock.UtcNow.AddMinutes(35);
}
return base.HandleSignInAsync(user, properties);
}
}
改变逻辑以设置 properties.ExpiresUtc
。
如果要替换内置的 CookieAuthenticationHandler
,请尝试在 Startup
中进行替换。
var descriptor =
new ServiceDescriptor(
typeof(CookieAuthenticationHandler),
typeof(CustomCookieAuthenticationHandler),
ServiceLifetime.Transient);
services.Replace(descriptor);