[英]change expiration auth cookie dynamically .net core identity
I have .NET Core 3.1 Web API app with .NET Core Identity.我有带有 .NET Core Identity 的 .NET Core 3.1 Web API 应用程序。 In Startup.cs
I have the following code:在Startup.cs
我有以下代码:
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?我可以动态覆盖 auth cookie 的过期时间吗? 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?也许SignInManager<...>
或UserManager<...>
中有一个选项可以覆盖这个值?
The Cookies for Identity is AspNetCore.Identity.Application, and its ExpireTimeSpan is set by HandleSignInAsync . Identity Cookie 是 AspNetCore.Identity.Application,其 ExpireTimeSpan 由HandleSignInAsync设置。
You can use cookie's OnSigningIn
event to dynamically set expire time for specific user :您可以使用 cookie 的OnSigningIn
事件为特定用户动态设置过期时间:
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)
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.