ASP.NETCore3.1中角色授权无法正常工作
创始人
2024-09-17 10:01:17
0
  1. 确保已经配置正确的身份验证和授权服务,并且已经使用正确的身份验证中间件。例如,可以使用下面的代码示例来配置身份验证和授权服务:

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options => { options.Cookie.HttpOnly = true; options.ExpireTimeSpan = TimeSpan.FromMinutes(30); options.LoginPath = new PathString("/Account/Login"); options.AccessDeniedPath = new PathString("/Account/AccessDenied"); });

services.AddAuthorization(options => { options.AddPolicy("AdminOnly", policy => policy.RequireRole("Admin")); });

  1. 确保已经将角色正确地分配给用户。例如,可以使用下面的代码示例来'Admin”角色分配给用户:

var user = new ApplicationUser { UserName = "admin@domain.com" }; await userManager.CreateAsync(user, "P@ssword"); await userManager.AddToRoleAsync(user, "Admin");

  1. 确保在确保当前用户已经通过身份验证之后再进行角色授权检查。例如,可以使用下面的代码示例来检查当前用户是否有'Admin”角色:

[Authorize(Policy = "AdminOnly")] public IActionResult AdminDashboard() { return View(); }

  1. 如果还是无法正常工作,可以尝试使用基于声明的授权而不是基于角色的授权。例如,可以使用下面的代码示例来设置声明:

var claims = new List { new Claim(ClaimTypes.Name, "admin@domain.com"), new Claim(ClaimTypes.Role, "Admin") };

var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); var principal = new ClaimsPrincipal(identity);

await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);

然后可以使用基于声明的授权检查:

[Authorize(Policy = "AdminOnly")] public IActionResult AdminDashboard() { var isAdmin = User.HasClaim(ClaimTypes.Role, "Admin"); return View(isAdmin); }

相关内容

热门资讯

pokemmo修改器手机版!f... pokemmo修改器手机版!fishpoker透视(透视)器-竟然必备是有挂1、pokemmo修改器...
透视详细!wepoker有没有... 透视详细!wepoker有没有挂(透视)wpk有那种辅助吗,教程积累(有挂透明挂)-哔哩哔哩wpk有...
拱趴大菠萝开挂方法!竞技联盟透... 拱趴大菠萝开挂方法!竞技联盟透视(透视)插件-确实总结真的有挂暗藏猫腻,小编详细说明拱趴大菠萝开挂方...
透视开挂!hhpoker德州挂... 透视开挂!hhpoker德州挂真的有吗(透视)约局吧开挂神器是真的吗,教程模板(有挂工具)-哔哩哔哩...
epoker免费透视脚本!德州... epoker免费透视脚本!德州透视是真的假的(透视)app-都是揭露真的有挂1)德州透视是真的假的辅...
透视科普!fishpoker透... 透视科普!fishpoker透视底牌(透视)wepoker私人辅助器,教程指南书(证实有挂)-哔哩哔...
aapoker万能辅助器!wp... aapoker万能辅助器!wpk辅助哪里买(透视)技巧-本来揭露有挂该软件可以轻松地帮助玩家将aap...
透视了解!hhpoker辅助软... 透视了解!hhpoker辅助软件下载(透视)wepoker有插件吗,教程大纲(真是有挂)-哔哩哔哩1...
wejoker辅助器要钱玩吗!... wejoker辅助器要钱玩吗!线上德州的辅助器是什么(透视)软件-果然解迷有挂线上德州的辅助器是什么...
透视关于!wepoker透视有... 透视关于!wepoker透视有用吗(透视)wpk可以透视吗,教程窍门(有挂教学)-哔哩哔哩1、完成w...