AuthorizeAttribute无法与ASP.NET Core 3.1中的端点路由一起使用
我将ASP.NET Core应用程序从2.2版迁移到了3.1版.我有一个具有 [Authorize]
属性的控制器,如下所示:
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
该策略在Startup.cs中的定义如下:
And the policy is defined in Startup.cs like this:
services.AddAuthorization(options =>
{
options.AddPolicy("MyPolicy",
policy =>
{
policy.RequireRole("MyRole");
policy.RequireScope("my-scope");
}
);
});
一切在2.2中都可以正常工作,但是在迁移到3.1并启用了端点路由之后,当存在 [Authorize]
属性时,无论策略规则如何(重定向到登录页面).当我删除 [Authorize]
并查看 User.Claims
时,我可以看到它确实具有必需的声明(例如,范围:my-scope,角色:MyRole).仅在启用端点路由的情况下才会发生这种情况,如果使用 UseMvc
,则一切正常.端点路由模式下的授权有什么问题?
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: Configure
方法如下所示:
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");
}
);
});