Getting custom claim value from bearer token (Web API)

Impworks picture Impworks · Oct 27, 2014 · Viewed 15.5k times · Source

In my ASP.NET Web API project I'm using bearer token authorization and I have added some custom claims to it, like this:

var authType = AuthConfig.OAuthOptions.AuthenticationType;
var identity = new ClaimsIdentity(authType);
identity.AddClaim(new Claim(ClaimTypes.Name, vm.Username));

// custom claim
identity.AddClaim(new Claim("CompanyID", profile.CompanyId.ToString()));

Is there any way I can access this additional claim value in the controller without an extra trip to the database?

Answer

Taiseer Joudeh picture Taiseer Joudeh · Oct 27, 2014

Sure, inside your protected controller you do the following:

 ClaimsPrincipal principal = Request.GetRequestContext().Principal as ClaimsPrincipal;
 var customClaimValue = principal.Claims.Where(c => c.Type == "CompanyID").Single().Value;