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

社会主义新天地 提交于 2021-02-11 09:59:08

问题


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 (i.e. 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();
    });
}

回答1:


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");
        }
    );
});


来源:https://stackoverflow.com/questions/60388730/authorizeattribute-not-working-with-endpoint-routing-in-asp-net-core-3-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!