I have .NET Core 3.1 Web API app with .NET Core Identity. In Startup.cs
I have the following code:
services.ConfigureApplicationCookie(options =>
{
options.ExpireTimeSpan = TimeSpan.FromHours(2);
});
But for some users I have different value of expiration time.
Can I overwrite expiration time of auth cookie dynamically? And if yes, what's the best way to do it? Maybe there is an option in SignInManager<...>
or UserManager<...>
that allow to overwrite this value?
The Cookies for Identity is AspNetCore.Identity.Application, and its ExpireTimeSpan is set by HandleSignInAsync .
You can use cookie's OnSigningIn
event to dynamically set expire time for specific user :
services.ConfigureApplicationCookie(opt => {
opt.Events.OnSigningIn = async (signinContext) => {
// you can use the pricipal to query claims
var email = signinContext.Principal.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;
if ("xxxx@hotmail.com".Equals(email))
{
// set the expiration time according to claims dynamically
signinContext.Properties.ExpiresUtc = DateTimeOffset.Now.AddSeconds(100);
signinContext.CookieOptions.Expires = signinContext.Properties.ExpiresUtc?.ToUniversalTime();
}
else
{
signinContext.Properties.ExpiresUtc = DateTimeOffset.Now.AddMinutes(60);
signinContext.CookieOptions.Expires = signinContext.Properties.ExpiresUtc?.ToUniversalTime();
}
};
});
I use this way:
await this._signInManager.SignInAsync(user, new Microsoft.AspNetCore.Authentication.AuthenticationProperties
{
ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(60)
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.