如何设置基于身份声明角色的.AspNetCore.Identity.Application Cookies有效期?

编程入门 行业动态 更新时间:2024-10-23 07:16:40
本文介绍了如何设置基于身份声明角色的.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有效期?

本文发布于:2023-11-17 04:58:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1608916.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何设置   有效期   角色   声明   身份

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!