首页 > 解决方案 > 在 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"))
...

标签: c#angularasp.net-coresingle-page-application

解决方案


你应该坚持原来的[Authorize(Roles="")]属性。

如此处所述:存储/分配经过身份验证的用户的角色

角色被添加到 HttpContext 的 IPrincipal。您可以创建一个 GenericPrincipal,在构造函数中解析角色列表并将其设置为 HttpContext.User。然后可以通过 User.IsInRole("role") 或 [Authorize(Roles="role")] 属性访问 GenericPrincipal

根据您的身份验证方案,您需要创建一个 GenericPrincipal 并在其中为所有请求添加角色,以便可以访问它们。

FormsAuthentication 的示例在上述答案中。


推荐阅读