Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Core Dynamic Expiration of Identity Cookie Based On Role

Right now we set the expiration of our Identity Cookie in the StartUp.cs of the project. We have a standard timeout and want to have a dynamic timeout based on the role of the logged in user. I'm looking for direction on how to access the Claims Role to set the Cookie expiration. Is middleware needed?

Basically I am looking for

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

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

});

this would also work

services.Configure<SecurityStampValidatorOptions>((options) => options.ValidationInterval = //BasedOnRole);
like image 687
Scott Clark Avatar asked Sep 15 '25 22:09

Scott Clark


1 Answers

The Cookies for Identity is AspNetCore.Identity.Application, and its ExpireTimeSpan is set by 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();
        }

You could implement your own CookieAuthenticationHandler by overring 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 == "[email protected]")
        {
            properties.ExpiresUtc = Clock.UtcNow.AddMinutes(15);
        }
        else
        {
            properties.ExpiresUtc = Clock.UtcNow.AddMinutes(35);
        }
        return base.HandleSignInAsync(user, properties);
    }
}

Change the logic to set properties.ExpiresUtc.

To replace built-in CookieAuthenticationHandler, try to replace it in Startup

            var descriptor =
            new ServiceDescriptor(
                typeof(CookieAuthenticationHandler),
                typeof(CustomCookieAuthenticationHandler),
                ServiceLifetime.Transient);
        services.Replace(descriptor);
like image 61
Edward Avatar answered Sep 18 '25 18:09

Edward