22

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?

Impworks
  • 2,647
  • 3
  • 25
  • 53

1 Answers1

32

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;
Taiseer Joudeh
  • 8,953
  • 1
  • 41
  • 45
  • How could I reuse this in a more centralized manner? I am using a Service layer which needs i.e. this `customClaimValue`. All controller actions need to send this value to the service before getting/posting data. – Steven Ryssaert Mar 07 '15 at 15:07
  • 1
    You can create custom filter which runs before hitting your action method – Taiseer Joudeh Mar 08 '15 at 22:54
  • 1
    Thanks, didn't know you could get the current request in a filter. Also a very nice blog you have there, Taiseer! – Steven Ryssaert Mar 09 '15 at 08:30
  • 1
    Personally, I do this in custom owin middleware early in the pipeline. Then I can access "CompanyID" from owin anywhere. – David Betz Jan 08 '16 at 14:20
  • How can we do it when the OWIN server is in an WebAPI Project that we use to get authentication from a Web project ? I have that WebAPI that centralizes all business/authentication for all of our apps and i have a website that need control regulation and use the API to get the bearer token. But then i want to regulate access to controllers in website based on the token i received, which contains claims such as Role, companyID etc.. – Ashallar Jun 28 '18 at 08:52