I am working with JWT tokens in my backend and my question is how I can read the value of the authorization header, when I have a [Authorize] annotation above my method. I need the token, because in its payload a user id is saved and I need the ID to perform several actions (of course the token gets verified first).
In my frontend, I am adding the authorize header as the following:
axios.post(finalurl, {accessToken: localStorage.accessToken}, {headers: {
'Authorization': `Bearer ${(localStorage.accessToken)}`
}})
In my backend:
[Authorize]
[HttpPut("{id}")]
public async Task<ActionResult<UserWithToken>> PutUser(int id, [FromForm] User user)
{
// ....
}
I know that it would also be possible to transfer the token as an object in the body, but this would make the thing more complicated, because when I am using this way I always have to create new Models that inherit from the object I want to transfer and gets an additional token attribute.
If you simply want to get the user ID and it's stored as a claim in the token, you can get it through the HttpContext
like so:
HttpContext.User?
.Claims?
.FirstOrDefault(c => c.Type == JwtRegisteredClaimNames.Sub)?
.Value
Of course, if you use a different claim type, you can replace JwtRegisteredClaimNames.Sub
with whatever your claim is called.
HttpContext.User
is the ClaimsPrincipal
of the user associated with the current request.