'Use jwt token to get orders for a current user
I have the following GET method:
[HttpGet]
[Authorize(Policy = OrderScopes.ProviderUserScopeName)]
public async Task<IActionResult> GetAllOrders()
{
var accessToken = await HttpContext.GetTokenAsync("access_token");
return Ok(await _mediator.Send(new GetAllOrdersQuery()));
}
If I run the above API I get all orders but I need to return the orders for the current user.
I have created accessToken to get the jwt token, but I got stuck here.
Do you have any ideas how can I get the orders for the current user?
Solution 1:[1]
Ideally, this is done in middleware before it even reaches your controller method.
But if you want to do it by hand, you first need to validate the JWT access_token extracted from your HTTP header. Failing to validate JWT tokens correctly is a common (and extremely dangerous) security issue.
To validate, use a ConfigurationManager<OpenIdConnectConfiguration> to retrieve the up-to-date signing keys, and then use JwtSecurityTokenHandler to actually validate the token. Be sure to use an up-to-date library version (avoiding the noop-algorithm security bug); and set ValidIssuer, ValidAudiences, ValidateIssuerSigningKey, and IssuerSigningKeys appropriately.
Once the JWT token is validated, then you will receive a ClaimsPrincipal as a result. On that principal is a claim with the name ClaimTypes.NameIdentifier; that is the unique identifier for that user. That's the identifier you should store or map somehow to an identifier used in your system.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Stephen Cleary |
