首页 新闻 会员 周边

ASP.NET Core 中如何动态更新 authentication cookies 中 Claims

0
悬赏园豆:30 [已解决问题] 解决于 2023-01-08 21:19

在不重新登录的情况下如何给 ClaimsIdentity 添加 Claim?

dudu的主页 dudu | 高人七级 | 园豆:31003
提问于:2023-01-08 15:56
< >
分享
最佳答案
0

参考 stackoverflow 上 How do I add a custom claim to authentication cookie 问题的回答,通过下面的代码解决了

var authenticateResult = await HttpContext.AuthenticateAsync();
if (authenticateResult.Succeeded)
{
    var claimsIdentity = authenticateResult.Principal.Identity as ClaimsIdentity;
    if (claimsIdentity != null)
    {
        if (!claimsIdentity.HasClaim(c => c.Type == CnblogsClaimTypes.BlogId))
        {
            claimsIdentity.AddClaim(new Claim(CnblogsClaimTypes.BlogId, user.BlogId.ToString()));
            await HttpContext.SignInAsync(authenticateResult.Principal, authenticateResult.Properties);
        }
    }
}
dudu | 高人七级 |园豆:31003 | 2023-01-08 21:18
其他回答(1)
0

重新生成cookie 不就行了么?

收获园豆:30
czd890 | 园豆:14412 (专家六级) | 2023-01-08 16:43

我想找到更优雅的方法

支持(0) 反对(0) dudu | 园豆:31003 (高人七级) | 2023-01-08 17:29
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册