c# - 在 ASP.NET Core 3 (3.0) SPA (Angular) 中如何正确检查用户角色?
问题描述
我一直在寻找如何在 SPA 中使用角色,Visual Studio (2019) 创建的基本项目非常好,但是[Authorize(Roles="")]
不能正常工作,所以我可以使用 Authorize 属性来检查用户是否实际登录但没有角色。
我现在在控制器中的方法是获取 user 和 use IsInRole()
,但这似乎是一个很大的开销,因为我应该已经拥有他的令牌,其中应该包含角色。
ClaimsPrincipal currentUser = this.User;
var currentUserId = currentUser.FindFirst(ClaimTypes.NameIdentifier).Value;
User user = await _userManager.FindByIdAsync(currentUserId);
if (await _userManager.IsInRoleAsync(user, "Admin"))
...
解决方案
你应该坚持原来的[Authorize(Roles="")]
属性。
如此处所述:存储/分配经过身份验证的用户的角色
角色被添加到 HttpContext 的 IPrincipal。您可以创建一个 GenericPrincipal,在构造函数中解析角色列表并将其设置为 HttpContext.User。然后可以通过 User.IsInRole("role") 或 [Authorize(Roles="role")] 属性访问 GenericPrincipal
根据您的身份验证方案,您需要创建一个 GenericPrincipal 并在其中为所有请求添加角色,以便可以访问它们。
FormsAuthentication 的示例在上述答案中。
推荐阅读
- python - 如何让 SWIG 公开的 C++ 类表现得像 python 中的元组?
- java - 有没有最好的方法来检查 Java 中的证书吊销状态?
- vue.js - Nuxt 部署和 IE 11
- xamarin - 我可以向 Xamarin.Mac 中的 NSPopUpButton 项目添加额外信息吗?
- html - 带有图像的社交媒体分享按钮(Facebook、Linkedin、Twitter)
- javascript - UL 项目的完整计数 - 包括嵌套项目
- php - 如何获取非对象 CodeIgniter 3.1 的“id”属性?
- python - 当我尝试 docker-compose up 时无法执行脚本 docker-compose
- docker - 如何在 Docker Compose 中修复此无效类型错误?
- jquery-select2 - Select2 在输入之外创建重复标签列表