I created a simple API with .NET 5.0 with a single controller action.
This action is protected with a policy:
[ApiController]
public class EnterpriseController : Controller
{
[HttpGet]
[Authorize(Policy = "Read")]
[Route("customers")]
public IActionResult GetCustomersAsync()
{
return Ok("Second request!");
}
}
The policy is passed if the calling token of my API contains a role "Customers.Read.All". This is done with setting the RoleClaimType to "roles":
services.Configure<JwtBearerOptions>(JwtBearerDefaults.AuthenticationScheme, options =>
{
var existingOnTokenValidatedHandler = options.Events.OnTokenValidated;
options.Events.OnTokenValidated = async context =>
{
await existingOnTokenValidatedHandler(context);
options.Authority = "https://login.microsoftonline.com/common";
options.TokenValidationParameters.RoleClaimType = "roles";
};
});
Then I add the policy:
services.AddAuthorization(options =>
{
options.AddPolicy("Read", policy => policy.RequireRole("Customers.Read.All"));
});
If I call my controller with a valid token, the first request returns "Forbidden" as a HTTP result.
If I call a second or third time, the call works as expected.
My whole example can be found here.
If I remove the policy from the controller and leave only the [Authorize], a valid token is enough for the call. Now my first call is also passed on the first try.
So I am sure that my problem is about the policies...
Do you have any ideas, why my first call is always forbidden?
Update:
This is the output:
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…