0

I am using asp.net web api 2.0 with asp.net identity 2.0. In GrantResourceOwnerCredentials , I have code like following to generate identity

var claimsIdentity = user.GenerateIdentityAsync(authType);

claimsIdentity is in turn used to create tokens. what I want to do is to create a subclass of ClaimsIdentity and create tokens from that subclass like

public class CustomClaimsIdentity: ClaimsIdentity{
     public CustomClaimsIdentity(int companyId){
       this.AddClaim('currentCompany', companyId.ToString());
     }
     public int GetCompanyId(){
        var claim = this.Claims.Single(x=>x.ClaimType == 'currentCompany');
        return int.Parse(claim.Value);    
     }
}

There will be some other functionality in this subclass too. I want to create tokens from this subclass and also want to have it (CustomClaimsIdentity) attached to my controllers in some way, so I can get company id of user and do some other stuff.

Muhammad Adeel Zahid
  • 17,474
  • 14
  • 90
  • 155
  • 1
    but you dont need to subclass ClaimsIdentity, you can create claims even with subclassing it, right? – harishr Feb 08 '15 at 13:46
  • No need to subclass. Just add claims and have extension methods that extract claims from `IPrincipal` - works much better than subclassing. I've tried. – trailmax Feb 08 '15 at 15:05
  • See this answer http://stackoverflow.com/a/28138594/809357 for sample of extension. – trailmax Feb 08 '15 at 15:07
  • yep, that is the simplest solution but I need to unit test those methods. Can I unit test extension methods with MS Test? – Muhammad Adeel Zahid Feb 08 '15 at 19:04
  • Why not? I successfully have a load of unit tests around the extension methods, though I have them in NUnit and XUnit. Tests are very simple: `ClaimsIdentity` and `ClaimsPrinciple` are quite basic objects that don't need to be mocked or anything special done to. So create your `ClaimsPrincipal` with required claims, apply the extension method and compare the results. I'd be surprised if MS Test can't do that. – trailmax Feb 09 '15 at 10:50

0 Answers0