Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of IClaimsTransformer?

In ASP.Net core lets you use an implementation of IClaimsTransformer.

You register it like this:

app.UseClaimsTransformation(o => o.Transformer = new MyClaimsTransformer());

Implementation

public class MyClaimsTransformer : IClaimsTransformer
{
    public Task<ClaimsPrincipal> TransformAsync(ClaimsTransformationContext context)
    {
        var identity = context.Principal.Identity as ClaimsIdentity;

        foreach (var claim in ci.Claims)
        {
           // you cannot modify claim.Type or claim.Value here
        }
    }
}

However ClaimsIdentity.Claims is read only property. Also Claim.Type, Claim.Value are readonly properties.

That means in the implementation of IClaimsTransformer you can only add new claims. You cannot remove or modify existing claims.

So whats the real use of IClaimsTransformer?

like image 726
LP13 Avatar asked Nov 03 '16 19:11

LP13


2 Answers

Did you notice the return type? It's ClaimsPrincipal.

You can construct a whole new ClaimsPrincipal, adding or changing whatever you like from the existing one and return it.

like image 58
blowdart Avatar answered Oct 11 '22 18:10

blowdart


the value of it is that you can supplement the claims beyond what is stored in the authentication cookie.

It is useful because only so much data can go into a cookie, if you try to put too much it will truncate.

So if you have a lot of claims or claims with a large payload you could maybe store that data in session and add it to the claimsprincipal using claims transformations. I don't think it is intended to remove claims that were stored in the cookie. If you want to add or control what claims go in the cookie you would do it in a custom IClaimsPrincipalFactory.

like image 20
Joe Audette Avatar answered Oct 11 '22 19:10

Joe Audette