Szel
Szel

Reputation: 120

Add persistent claim with Asp.Net Core Identity

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.

Upvotes: 0

Views: 2899

Answers (2)

Denny Jacob
Denny Jacob

Reputation: 395

"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.

Upvotes: 0

Karney.
Karney.

Reputation: 5031

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>();

Upvotes: 3

Related Questions