Right now we set the expiration of our Identity Cookie in the StartUp.cs of the project. We have a standard timeout and want to have a dynamic timeout based on the role of the logged in user. I'm looking for direction on how to access the Claims Role to set the Cookie expiration. Is middleware needed?
Basically I am looking for
services.AddIdentity<ApplicationUser, IdentityRole>(options => {
options.Cookies.ApplicationCookie.ExpireTimeSpan = //BasedOnRole);
});
this would also work
services.Configure<SecurityStampValidatorOptions>((options) => options.ValidationInterval = //BasedOnRole);
The Cookies for Identity
is AspNetCore.Identity.Application
, and its ExpireTimeSpan
is set by 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();
}
You could implement your own CookieAuthenticationHandler
by overring HandleSignInAsync
.
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 == "[email protected]")
{
properties.ExpiresUtc = Clock.UtcNow.AddMinutes(15);
}
else
{
properties.ExpiresUtc = Clock.UtcNow.AddMinutes(35);
}
return base.HandleSignInAsync(user, properties);
}
}
Change the logic to set properties.ExpiresUtc
.
To replace built-in CookieAuthenticationHandler
, try to replace it in Startup
var descriptor =
new ServiceDescriptor(
typeof(CookieAuthenticationHandler),
typeof(CustomCookieAuthenticationHandler),
ServiceLifetime.Transient);
services.Replace(descriptor);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With