简体   繁体   中英

AuthorizeAttribute not working with Endpoint Routing in ASP.NET Core 3.1

I migrated my ASP.NET Core application from version 2.2 to 3.1. I have a controller with [Authorize] attribute like this:

[ApiController]
[Authorize(policy: "MyPolicy")]
[Route("api/v{version:apiVersion}/[controller]")]
public class MyController : Controller

And the policy is defined in Startup.cs like this:

services.AddAuthorization(options =>
{
    options.AddPolicy("MyPolicy",
        policy =>
        {
            policy.RequireRole("MyRole");
            policy.RequireScope("my-scope");
        }
    );
});

Everything worked fine in 2.2, but after migrating to 3.1 and enabling Endpoint Routing, this controller began to refuse requests to any endpoint when [Authorize] attribute is present, regardless of policy rules (redirecting to the Login page). When I remove [Authorize] and look at User.Claims , I can see that it does have the required claims (ie scope: my-scope, role: MyRole). This happens only if Endpoint Routing is enabled, in case of using UseMvc everything works properly. What's wrong with Authorization in Endpoint Routing mode?

UPD: The Configure method looks like this:

public void Configure(IApplicationBuilder app)
{
    app.UseHttpsRedirection();
    app.UseStaticFiles();

    app.UseIdentityServer();
    app.UseRouting();

    app.UseAuthentication();
    app.UseAuthorization();

    app.UseEndpoints(endpoints => {
        endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
        endpoints.MapControllers();
        endpoints.MapRazorPages();
    });
}

Got it working after explicitly setting Authentication Scheme in the policy definition:

services.AddAuthorization(options =>
{
    options.AddPolicy("MyPolicy",
        policy =>
        {
            policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme);
            policy.RequireRole("MyRole");
            policy.RequireScope("my-scope");
        }
    );
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM