本文介绍了如何设置基于身份声明角色的.AspNetCore.Identity.Application Cookies有效期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在根据登录用户的声明角色来设置.AspNetCore.Identity.Application Cookie的过期时间.

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.

ConfigureServices中的所有配置选项中,我可以访问cookie属性,但不能访问用户声明.因此,我无法动态设置到期时间.我们正在使用Microsoft.AspNetCore.Identity SignInManager进行身份验证.

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?

推荐答案

Cookie身份验证处理程序将在生成身份验证票证之前触发OnSigningIn事件,请参见 GitHub :

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

}

(请注意第await Events.SigningIn(signInContext);行)

这为我们提供了使用Events.OnSigningIn修改到期时间的机会.因此,在您的ConfigureServices()方法中,添加如下代码:

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

    };
});

它将按预期工作.

这篇关于如何设置基于身份声明角色的.AspNetCore.Identity.Application Cookies有效期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 16:56