How to set .AspNetCore.Identity.Application Cookies expiration based on Identity Claims Role?

你说的曾经没有我的故事 提交于 2020-05-14 08:45:08

问题


I'm looking to set the .AspNetCore.Identity.Application Cookie's expiration time based on the role of claims of a user that logs in.

In all of the configure options in ConfigureServices I have access to cookie properties but no access to user claims. Therefore I cannot dynamically set the expiration time. We are using Microsoft.AspNetCore.Identity SignInManager to authenticate.

Can anyone point me in the right direction as to what class I need to override or what middleware I need to register to achieve this?


回答1:


The Cookie Authentication Handler will trigger OnSigningIn event before generating an authentication ticket, see source code on GitHub :

protected async override Task HandleSignInAsync(ClaimsPrincipal user, AuthenticationProperties properties)
{
    // ...
    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();
    }

    var ticket = new AuthenticationTicket(signInContext.Principal, signInContext.Properties, signInContext.Scheme.Name);
    // ...

}

(Note the line await Events.SigningIn(signInContext); )

This gives us a chance to modify the expiration time using Events.OnSigningIn. So in your ConfigureServices() method, add codes as below :

services.ConfigureApplicationCookie(opt =>{
    opt.Events.OnSigningIn = async(signinContext)=>{

        // you can use the pricipal to query claims and roles as you need
        var x = signinContext.Principal.Claims.First(c=>c.Type=="X1" && ...); 
        // set the expiration time according to claims/roles dynamically 
        signinContext.Properties.ExpiresUtc = DateTimeOffset.Now.AddSeconds(100);
        signinContext.CookieOptions.Expires = signinContext.Properties.ExpiresUtc?.ToUniversalTime();

    };
});

It will work as expected.



来源:https://stackoverflow.com/questions/52952488/how-to-set-aspnetcore-identity-application-cookies-expiration-based-on-identity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!