Home > Software design >  Get custom JWT Claim in each controller method injected
Get custom JWT Claim in each controller method injected

Time:04-14

i have a .Net 6 API where I use JWT for auth. My JWT token has a custom claim: "customId".

In every method of all my controllers, I want to get the customId.

I already know that I can get it using: HttpContext (var identity = HttpContext.User.Identity as ClaimsIdentity;(...))

Or User (User.Claims.SingleOrDefault(...))

But i want to get it injected directly on each authorized controller (or method), so I don't have to get it from HttpContext or User each time.

Does anyone know how I could do it? Thanks!

CodePudding user response:

You can create a base controller class and define getting the claim implementation inside.

Something like:

public abstract class BaseController : ControllerBase
{
    protected string? GetCustomIdClaimValue()
    {
        
        return HttpContext?.User?.Claims?.FirstOrDefault(o => o.Type == "sometype")?.Value;
    }
}

Then you can declare every controller as a child of this class:

[Authorize]
[Route("api/[controller]")]
[ApiController]
public class ValuesController : BaseController
{
    [HttpGet]
    public IActionResult Get()
    {
        return Ok(GetCustomIdClaimValue());
    }
}
  • Related