gpt4 book ai didi

c# - .NET Core 基于角色的身份 Cookie 动态过期

转载 作者:行者123 更新时间:2023-11-30 20:15:43 25 4
gpt4 key购买 nike

现在我们在项目的 StartUp.cs 中设置身份 Cookie 的过期时间。我们有一个标准的超时,并希望有一个基于登录用户角色的动态超时。我正在寻找有关如何访问声明角色以设置 Cookie 过期的指导。是否需要中间件?

基本上我在找

services.AddIdentity<ApplicationUser, IdentityRole>(options => {

options.Cookies.ApplicationCookie.ExpireTimeSpan = //BasedOnRole);

});

这也行

services.Configure<SecurityStampValidatorOptions>((options) => options.ValidationInterval = //BasedOnRole);

最佳答案

Identity 的Cookie 是AspNetCore.Identity.Application,其ExpireTimeSpanHandleSignInAsync 设置.

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);

关于c# - .NET Core 基于角色的身份 Cookie 动态过期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52746378/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com