0
votes

I have build custom authorization module based on Identity. Permissions from db are loaded to Claims with UserClaimsPrincipalFactory which works great but happens only on login.

When granting new permission I think I have two options:

  1. Add claim to current ClaimsIdentity
  2. Refresh all claims by recreating identity

The problem is when i try to add claim with user.Identity.AddClaim() it doesn't persist when page is reloaded. And I cannot find information how to reload ClaimsIdentity.

1
the identity is recreated per request. why can't you store the new claim? - Daniel A. White
user.Identity.AddClaim() is just a method to add claim on ClaimsIdentity which is of course not related to Identity, what you need is UserManager.AddClaimAsync which should persist your claim. - King King
@KingKing UserManager just saves claim in db I don't want that. I am using UserClaimsPrincipalFactory (docs.microsoft.com/en-us/dotnet/api/…) to generate claims dynamically but methods in it CreateAsync and GenerateClaimsAsync are only called on sign in. - Szel

1 Answers

2
votes

I am not sure when project need to add the external claims. Identity is based on cookie, every request will carry the cookie, so the identity can parse the cookie as the claims. If you want to reload ClaimsIdentity, you need to reuse the method SignInAsync to regenerate cookie. But there is a global method IClaimsTransformation can help you add the temporary claim according to different situation.

public class Tanstromer : IClaimsTransformation
{
    public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
    {
        var claims = new List<Claim> { };
        var identity = principal.Identity as ClaimsIdentity;
        identity.AddClaim(new Claim("",""));

        //you can add some justification here
        var userPrinicpal = new ClaimsPrincipal(identity);
        return Task.FromResult(principal); 
    }
}

Add it in ConfigureService

services.AddScoped<IClaimsTransformation, Tanstromer>();