问题
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