5

It is possible to bind actions' parameters via:

  • [FromBody] Request body
  • [FromForm] Form data in the request body
  • [FromHeader] Request header
  • [FromQuery] Request query string parameter
  • [FromRoute] Route data from the current request
  • [FromServices]

I often need to extract something from a JWT, almost always the id (primary key). So I do this (ignore error checking for now):

var id = int.Parse(base.User.FindFirst(ClaimTypes.NameIdentifier)?.Value);

It would be great if I could put that into an attribute binder that would work like this:

public IActionResult doStuff([FromBody] MyModel model, [FromJwt] int id) {
  // id works automatically
}

Or maybe [FromJwtId] instead to make it simpler.

Is such a thing possible?

lonix
  • 14,255
  • 23
  • 85
  • 176
  • I know I could put it into a base class, but I want to get this to work instead. Also I could later add checks that if the data is invalid to automatically return a 400 or similar. – lonix May 14 '19 at 14:09

2 Answers2

4

I think it is possible to create such attributes using HttpParameterBinding.

Microsoft has a tutorial on that.

bolkay
  • 1,881
  • 9
  • 20
  • 1
    Excellent! It was deeply buried under a section called "guidance", so never saw it! :-) Pity there's no easier way to do it, but I know where to start, thanks! – lonix May 14 '19 at 16:13
-1

Everything you need from JWT token is available in the claims, you can access to them by the identity.

If you want some recurrent, an approach will be create an abstract class that inherits from Controller and your Controllers inherits from that BaseController to do the implementation for a reusable and quick access or implements some UserServices that give everything related to the user, register it in the StartUp file and NetCore inyect it for you

(System.Security.Claims.ClaimsIdentity)User.Identity
Zach dev
  • 1,610
  • 8
  • 15