从MVC迁移到ASP.NET Core 3.1中的端点路由时,AuthorizeAttribute的角色不起作用 [英] AuthorizeAttribute with Roles not working when migrating from MVC to Endpoint Routing in ASP.NET Core 3.1

查看:46
本文介绍了从MVC迁移到ASP.NET Core 3.1中的端点路由时,AuthorizeAttribute的角色不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正尝试将我的项目从.UseMVC(asp.net核心2.2兼容样式)升级到.UseEndpoint路由,并且对于所有请求,我都将重定向到我的验证失败页面.它与声明有关-如果我删除[Authorize(Roles ="Admin")]的角色部分以简单地[Authorize],则它起作用.似乎并没有处理分配给用户的声明.

这似乎与 AuthorizeAttribute无法与ASP.NET Core 3.1中的端点路由一起使用

以下段落是链接文章的摘录,但经过修改以反映我的问题版本

在2.2中一切正常,但在迁移到3.1并启用后端点路由,此控制器开始拒绝任何请求端点,当[Authorize(Roles ='Admin;)]属性存在时.当我删除时角色="并查看User.Claims,我可以看到它确实具有必需的索赔/角色.有时候是这样的仅在启用端点路由的情况下(在使用UseMvc的情况下)一切正常.端点授权有什么问题路由模式?

摘录自Startup.cs

  app.UseSession();app.UseRouting();app.UseAuthentication();app.UseAuthorization();app.UseResponseCompression();//将用户角色添加为他的身份声明,以便出于身份验证目的进行选择app.Use((context,next)=>{var userId = context.User.Identity.Name;如果(userId == null){返回next();}...var role = resourceDataAccess.GetRolesForUser(userId);if(角色!= null){var Claims = role.Select(role => new Claim(ClaimTypes.Role,role.RoleEnum.ToString())).ToList();var appIdentity = new ClaimsIdentity(claims);context.User.AddIdentity(appIdentity);}返回next();});app.UseEndpoints(endpoints =>{endpoints.MapHub< AppHub>("api/apphub");endpoints.MapControllerRoute("default","api/{controller = Account}/{action = SignIn}/{id?}"));endpoints.MapControllerRoute("catch-all","api/{* url}",new {controller ="Utility",action ="NotFoundPage"});}); 

解决方案

事实证明,因为我们使用的是app.Use()中间件来填充数据库中的用户角色,因此需要在UseAuthorisation之前调用它在执行授权之前已加载角色.(就像@CamiloTerevinto的评论一样)

  app.UseSession();app.UseRouting();app.UseAuthentication();//将用户角色添加为他的身份声明,以便出于身份验证目的进行选择app.Use((context,next)=>{...}//将授权中间件设置为仅在加载用户角色后才运行.app.UseAuthorization();app.UseResponseCompression(); 

I'm trying to upgrade my project from .UseMVC (asp.net core 2.2 compat style) to .UseEndpoint Routing and I'm getting re-directed to my suthentication failed page for all my requests. It has to do with the Claims - If I remove the role part of [Authorize(Roles = "Admin")] to simply [Authorize] then it works. It seems that it isn't picking up the claims that are assigned to the user.

It seems to be a very similar issue as AuthorizeAttribute not working with Endpoint Routing in ASP.NET Core 3.1

The following paragraph is an excerpt from the linked post but modified to reflect my version of the issue

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(Roles = "Admin")] attribute is present. When I remove "Roles =" part and look at User.Claims, I can see that it does have the required claims/roles. 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?

Excerpt from Startup.cs

 app.UseSession();
    
 app.UseRouting();
    
 app.UseAuthentication();
 app.UseAuthorization();
 app.UseResponseCompression();
 //Add the users Roles as claims to his identity so that it is picked up for authentication purposes
 app.Use((context, next) =>
 {
     var userId = context.User.Identity.Name;
     if (userId == null)
     {
         return next();
     }
    
     ...
        
     var roles = resourceDataAccess.GetRolesForUser(userId);
     if (roles != null)
     {
         var claims = roles.Select(role => new Claim(ClaimTypes.Role, role.RoleEnum.ToString())).ToList();
    
         var appIdentity = new ClaimsIdentity(claims);
         context.User.AddIdentity(appIdentity);
     }
    
     return next();
 });
 app.UseEndpoints(endpoints =>
 {
     endpoints.MapHub<AppHub>("api/apphub");
     endpoints.MapControllerRoute("default", "api/{controller=Account}/{action=SignIn}/{id?}");
     endpoints.MapControllerRoute("catch-all", "api/{*url}",
             new {controller = "Utility", action = "NotFoundPage"});
 });

解决方案

It turns out since we were using app.Use() middleware to fill in the user's roles from the DB, it needed to be called before UseAuthorisation so that the roles were loaded before authorisation was performed. (Like @CamiloTerevinto's comment)

 app.UseSession();
    
 app.UseRouting();
    
 app.UseAuthentication();
 //Add the users Roles as claims to his identity so that it is picked up for authentication purposes
 app.Use((context, next) =>
 {
   ...
 }
 //Setup the authorisation middleware to run only after we have loaded the users roles.
 app.UseAuthorization();
 app.UseResponseCompression();
 

这篇关于从MVC迁移到ASP.NET Core 3.1中的端点路由时,AuthorizeAttribute的角色不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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