简体   繁体   中英

How to get JWT Claims once for all WebApi Controllers

I have several claims added to my JWT token. In ever method, of every controller inside my API I am getting the identity and inspecting these claims. I'd like to reduce the duplication of code and obtain my claims from a common place; possibly assigning them inside startup.cs.

For example, I have a DemoController that implements basic CRUD operations. The same code tends to appear in all of my methods, in all of my controllers:

var identity = (ClaimsPrincipal)Thread.CurrentPrincipal;

var region = identity.Claims.Where(c => c.Type == ClaimType.Region).Select(c => c.Value).SingleOrDefault();

var role = identity.Claims.Where(c => c.Type == ClaimType.Role).Select(c => c.Value).SingleOrDefault();

var responseType = identity.Claims.Where(c => c.Type == ClaimType.ResponseType).Select(c => c.Value).SingleOrDefault();  

If (region == "some region")
{
}

Is there any way I can avoid duplicating this code all over the my API? I'd like to use an object that can be shared throughout the WebApi controller so that I can write my code like this instead:

if(ApiUser.Region == "Some Region")
{
  // DO SOMETHING
}

I am already using Ninject for dependency injection. I thought it may be possible to create my ApiUser object in the Startup.cs where the claims would be assigned and then inject the ApiUser into each controller but I'm not totally sure how to do this, if it's possible or if there is an better viable alternative.

All suggestions are welcome!

You can create an implementation of a ClaimsAuthenticationManager to perform the looking up of claims or even adding additional custom claims to your JWT.

public class MyClaimsAuthenticationManager : ClaimsAuthenticationManager
{
    public override ClaimsPrincipal Authenticate(string resourceName, ClaimsPrincipal incomingPrincipal)
    {
        if (incomingPrincipal != null && incomingPrincipal.Identity.IsAuthenticated)
         // build up your ApiUser class here

    }
    return incomingPrincipal;
}

You can then use your ApiUser class to make your checks in each controller; or even better, using a custom AuthorizationAttribute for each type of check you want to do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM