gpt4 book ai didi

c# - 从 MVC 迁移到 ASP.NET Core 3.1 中的端点路由时,带有角色的 AuthorizeAttribute 不起作用

转载 作者:行者123 更新时间:2023-12-04 12:57:21 25 4
gpt4 key购买 nike

我正在尝试将我的项目从 .UseMVC(asp.net 核心 2.2 兼容样式)升级到 .UseEndpoint Routing,并且我的所有请求都被重定向到我的身份验证失败页面。它与声明有关 - 如果我将 [Authorize(Roles = "Admin")] 的角色部分删除为简单的 [Authorize] 那么它就可以工作了。它似乎没有接受分配给用户的声明。
这似乎是一个与 AuthorizeAttribute not working with Endpoint Routing in ASP.NET Core 3.1 非常相似的问题
以下段落是链接帖子的摘录,但经过修改以反射(reflect)我的问题版本

Everything worked fine in 2.2, but after migrating to 3.1 and enablingEndpoint Routing, this controller began to refuse requests to anyendpoint when [Authorize(Roles = "Admin")] attribute is present. When I remove"Roles =" part and look at User.Claims, I can see that it does have therequired claims/roles. This happensonly if Endpoint Routing is enabled, in case of using UseMvceverything works properly. What's wrong with Authorization in EndpointRouting mode?


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

最佳答案

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

 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();

关于c# - 从 MVC 迁移到 ASP.NET Core 3.1 中的端点路由时,带有角色的 AuthorizeAttribute 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65028989/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com