0

I'm developing an .NET Web API and using JWT tokens to secure it. In my research of the best way to implement it, i decided to use the jwt claims to also limit the access to content, depending on specific claims present on the token. I can now manually verify if for example, a userId matches with the userId of a record's userId and return it if it's a match, but this is very tedious and not quickly adds up the amount of code just to do the same task...

Is there a way to implement something like an action filter to apply the claims to every request and return only the records that match the information in the token?

Thanks everyone in advance

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • Task 1 - Creating a Custom Filter to Catch a Controller's Request https://learn.microsoft.com/en-us/aspnet/mvc/overview/older-versions/hands-on-labs/aspnet-mvc-4-custom-action-filters – Radost Aug 16 '22 at 11:37

1 Answers1

0

See this implementation on this project. https://github.com/cuongle/WebApi.Jwt/blob/master/WebApi.Jwt/Filters/JwtAuthenticationAttribute.cs

It's a simple scenario.

  1. JWT contains a user's id or some claims.

  2. You have a WEB API endpoint like ("GetCurrentUserData()") decorated with your custom ActionFilterAttribute.

  3. Within that method you will call a helper function that will read the current request user claims and return them in a simple form (like user id).

See: Get claims from a WebAPI Controller - JWT Token,

Then within the method you can query/filter your returned data based on the Id/Claims of the current user of the request.

Anestis Kivranoglou
  • 7,728
  • 5
  • 44
  • 47