Search code examples
asp.net-coreasp.net-core-webapiidentityserver4claims-based-identity

Update logged Identity claims when add new claims


I have a .net core web api application with angular. I use AspNetCore Identity. I have a claim table with userId and value colums. The createnewuser method call from angular site, and they call to register user method. There no any problem here.

I wanna add new claim into httpcontext current user claims list. I'd tried but it is not help me.

Added a claim to an existing HttpContext User

But I can see added new claim into _httpContext.HttpContext.User.Claims when re-authenticate with new token. How can I see add new claim into current identity (_httpContext.HttpContext.User.Claims)?

And I got current user Id value from httpontext.

var parentId = _httpContext.HttpContext.User.Claims?.FirstOrDefault(p => p.Type == "uid");
                     if (parentId != null && parentId.Value != null)
                     {
                        await _IdentityService.AddClaimAsync(new RegisterRequest()
                         {
                          "newclaim" = "new-claim-key",
                          userId = parentId.Value
                      });

Solution

  • I think best wasy get claims from db who logged used like that:

    var claimList = userManager.
    GetClaimsAsync(await_userManager.GetUserAsync(_httpContext.HttpContext.User))
    

    Although this is not a very accurate method, it is the most reliable method. This way you can get the latest claim list in db