AuthorizeAttribute无法与ASP.NET Core 3.1中的端点路由一起使用 [英] AuthorizeAttribute not working with Endpoint Routing in ASP.NET Core 3.1

查看:102
本文介绍了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");
        }
    );
});

这篇关于AuthorizeAttribute无法与ASP.NET Core 3.1中的端点路由一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆