Search code examples
asp.net-corejwtauthorization

Problem with JWT authorization in ASP.NET Core


I'm sending a JWT to my endpoint using the Authorization header with the value Bearer <encoded jwt>. Here's the payload of the JWT:

{
  "sub": "1",
  "email": "[email protected]",
  "jti": "4dabc47a-c524-4f23-b271-420235822d3d",
  "role": "admin",
  "exp": 1682255987,
  "iss": "http://localhost:5000",
  "aud": "http://localhost:5000"
}

However, when I make the request, I receive a 403 Forbidden response instead of the expected 201 Created. Here's the code for my endpoint in controller:

[Authorize("admin")]
[HttpPost]
public async Task<IActionResult> Post([FromBody] ExampleRequest request)
{
    // actual code returning Created()
}

authorization config in Program.cs:

builder.Services.AddAuthorization(options =>
    options.AddPolicy("admin", policy =>
        policy.RequireClaim("role", "admin")));

I am sure that token hasn't expired. Response headers does't contain anything useful. I have added authorization middleware to app (app.UseAuthorization();). Can somebody tell me what I did wrong?

I believe i included all necessary details, but here is source code if you want to check it out.

Thanks


Solution

  • It is not what i exactly wanted, but i used ClaimTypes.Role instead of "admin" for role key, deleted AddPolicy in Program.cs, replaced [Authorize("admin")] with [Authorize(Roles = "admin")] aaaand it somehow worked! It it's not answer to question (because it uses roles instead of policies, as i initialy wanted) to be honest, but it's an good solution and i'll stick with it.