Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
261 views
in Technique[技术] by (71.8m points)

c# - If using policy based authentication, the first call to .net core API is forbidden

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:

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...