Bind ASP.NET Core action parameter to JWT claim

lon*_*nix 5 c# model-binding jwt asp.net-core asp.net-core-2.2

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);
Run Code Online (Sandbox Code Playgroud)

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
}
Run Code Online (Sandbox Code Playgroud)

Or maybe [FromJwtId] instead to make it simpler.

Is such a thing possible?

bol*_*kay 4

我认为可以使用创建此类属性HttpParameterBinding

微软有一个关于这方面的教程