基于角色的.NET Core动态身份验证Cookie

Sco*_*ark 2 .net c# .net-core asp.net-core

现在,我们在项目的StartUp.cs中设置Identity Cookie的到期时间。我们有一个标准的超时时间,并且希望根据登录用户的角色进行动态超时。我正在寻找有关如何访问Claims Role来设置Cookie到期的方向。需要中间件吗?

基本上我在找

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

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

});
Run Code Online (Sandbox Code Playgroud)

这也可以

services.Configure<SecurityStampValidatorOptions>((options) => options.ValidationInterval = //BasedOnRole);
Run Code Online (Sandbox Code Playgroud)

Tao*_*hou 6

Cookies IdentityAspNetCore.Identity.ApplicationExpireTimeSpanHandleSignInAsync设置。

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();
        }
Run Code Online (Sandbox Code Playgroud)

您可以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);
    }
}
Run Code Online (Sandbox Code Playgroud)

更改逻辑以设置properties.ExpiresUtc

要替换内置的CookieAuthenticationHandler,请尝试替换为Startup

            var descriptor =
            new ServiceDescriptor(
                typeof(CookieAuthenticationHandler),
                typeof(CustomCookieAuthenticationHandler),
                ServiceLifetime.Transient);
        services.Replace(descriptor);
Run Code Online (Sandbox Code Playgroud)