简体   繁体   中英

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?

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

Microsoft has a tutorial on that.

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

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