Impworks
Impworks

Reputation: 2818

Getting custom claim value from bearer token (Web API)

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?

Upvotes: 22

Views: 17311

Answers (1)

Taiseer Joudeh
Taiseer Joudeh

Reputation: 9043

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;

Upvotes: 32

Related Questions