本文介绍了添加了对现有 HttpContext 用户的声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个带有端点的 ASP.NET Core 3.1 Web API,用于向现有用户标识添加新声明.声明成功添加到身份,但是,在后续请求中,添加的声明不在声明集合中,因此不可用.我还尝试添加一个新身份,为其分配声明,类似地在后续请求中,添加的身份不在身份集合中.有什么想法吗?

I'm developing an ASP.NET Core 3.1 Web API with an endpoint to add a new claim onto an existing User Identity. The claim successfully adds to the identity, however, on subsequent requests, the added claim is not in the collection of claims, so not available. I have also tried adding a new identity, assigning it the claim, similarly on subsequent requests, the added identity is not in the collection of identities. Any ideas?

var claims = new List<Claim>()
{
    new Claim("token","value")
}

var identity = httpContextAccessor.HttpContext.User.Identities.FirstOrDefault();
identity.AddClaims(claims);

推荐答案

您需要使用更新的 ClaimsIdentity 调用 _signInManager.Context.SignInAsync.

You need to call _signInManager.Context.SignInAsync with updated ClaimsIdentity.

这是一个工作演示:

1.使用新的ClaimsIdentity登录的扩展:

1.Extension for signin with new ClaimsIdentity:

public class CustomClaimsCookieSignInHelper<TIdentityUser> where TIdentityUser : IdentityUser
{
    private readonly SignInManager<TIdentityUser> _signInManager;

    public CustomClaimsCookieSignInHelper(SignInManager<TIdentityUser> signInManager)
    {
        _signInManager = signInManager;
    }

    public async Task SignInUserAsync(ClaimsIdentity claimsIdentity)
    {
        await _signInManager.Context.SignInAsync(IdentityConstants.ApplicationScheme, new ClaimsPrincipal(claimsIdentity));
    }

}

2.注册CustomClaimsCookieSignInHelper:

services.AddTransient<CustomClaimsCookieSignInHelper<IdentityUser>>();

3.更新用户声明:

public class IndexModel : PageModel
{
    private readonly CustomClaimsCookieSignInHelper<IdentityUser> _signInHelper;

    public IndexModel(CustomClaimsCookieSignInHelper<IdentityUser> signInHelper)
    {
        _signInHelper = signInHelper;
    }

    public async Task<IActionResult> OnGetAsync()
    {
        var claims = new List<Claim>()
        {
            new Claim("token","value")
        };

        var identity = HttpContext.User.Identities.FirstOrDefault();
        identity.AddClaims(claims);
        await _signInHelper.SignInUserAsync(identity);
        return Page();
    }
}

顺便说一句,如果你使用jwt authentication,当服务器端得到带有令牌的API调用时,AddJwtBearer将解码令牌,验证令牌并使用户进行身份验证,你可以在 OnTokenValidated 或自定义中间件中添加新声明.但是这些声明不会在下一次 api 调用中持续存在.因此,如果您想在另一个请求中获得更新的声明,则必须发出一个新的令牌.

BTW,if you use jwt authentication,When server side get the API call with token , the AddJwtBearer will decode token ,validate token and make user authenticated, you can add new claims either in OnTokenValidated or in custom middleware. But the claims won't persist in next api calls.So if you want to get updated claim in another request, a new token must be issued.

这篇关于添加了对现有 HttpContext 用户的声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 01:22