0

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.

3
  • the identity is recreated per request. why can't you store the new claim? Commented Feb 22, 2021 at 21:23
  • 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. Commented Feb 22, 2021 at 21:31
  • @KingKing UserManager just saves claim in db I don't want that. I am using UserClaimsPrincipalFactory (learn.microsoft.com/en-us/dotnet/api/…) to generate claims dynamically but methods in it CreateAsync and GenerateClaimsAsync are only called on sign in. Commented Feb 22, 2021 at 22:52

2 Answers 2

3

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>();
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, I moved my logic from UserClaimsPrincipalFactory to IClaimsTransformation.
this is good solution but how can I call the TransformAsync metot another class?
Why is your class called Tanstromer?
0

"I am not sure when project need to add the external claims."

Apps that rely on 3rd party authentication will need to add additional app specific claims to the principal that is created. I have used TransformAsync() in those scenarios and had the same challenge with persisting the "appended" claims in certain situations.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.