Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind ASP.NET Core action parameter to JWT claim

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?

like image 484
lonix Avatar asked May 14 '19 14:05

lonix


1 Answers

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

Microsoft has a tutorial on that.

like image 86
bolkay Avatar answered Nov 02 '22 04:11

bolkay