现在,我们在项目的StartUp.cs中设置Identity Cookie的到期时间。我们有一个标准的超时时间,并且希望根据登录用户的角色进行动态超时。我正在寻找有关如何访问Claims Role来设置Cookie到期的方向。需要中间件吗?
基本上我正在寻找
services.AddIdentity<ApplicationUser, IdentityRole>(options => {
options.Cookies.ApplicationCookie.ExpireTimeSpan = //BasedOnRole);
});
这也可以
services.Configure<SecurityStampValidatorOptions>((options) => options.ValidationInterval = //BasedOnRole);
答案 0 :(得分:5)
Identity
的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();
}
您可以通过覆盖CookieAuthenticationHandler
来实现自己的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 == "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);
答案 1 :(得分:0)
您好,您可以添加Cookie
services.ConfigureApplicationCookie(options =>
{
options.AccessDeniedPath = "/Identity/Account/AccessDenied";
options.Cookie.Name = "YourAppCookieName";
options.Cookie.HttpOnly = true;
options.ExpireTimeSpan = TimeSpan.FromMinutes(60);
options.LoginPath = "/Identity/Account/Login";
// ReturnUrlParameter requires
//using Microsoft.AspNetCore.Authentication.Cookies;
options.ReturnUrlParameter = CookieAuthenticationDefaults.ReturnUrlParameter;
options.SlidingExpiration = true;
});