如何在客户端获取用户角色?

How to get user role on client side?

我正在开发具有 ASP.NET 核心后端的 Angular 网络应用程序。从用于个人用户帐户身份验证的内置 "ASP.NET Core application with Angular" 模板项目开始。我的问题是在客户端获得经过身份验证的用户角色(我想在角色中处理守卫和菜单)。

现在我有 API 从后端返回用户角色的端点。

当我需要了解用户的角色时,我会调用这个端点。例如。菜单处理 导航-menu.component.ts

但我知道这不是最好的解决方案。可能的代码重复等

还有其他解决办法吗?

我尝试了另一种解决方案,但效果不佳。 在 authorize service 中,当在登录期间建立用户配置文件(任何)时,我应该将角色附加到配置文件。

感谢任何建议

如果您发布的是代码片段而不是图片,那会更有帮助。

但是,根据我在您的代码中看到的情况,您是在另一个订阅内进行订阅,这是一种不好的做法。

这是你应该如何做的:

this.authorizeService
      .getUser()
      .pipe(
        // switchMap completes the previous observable and subscribe to the next one
        // the argument (user) is the data you get from the previous observable
        switchMap(user => (user ? this.authorizeService.getUserRoles(user.name) : of(null))))
      .subscribe(roles => this.roles = roles);

如果您有后台代码的权限,最好将 2 个端点合二为一,... 例如。您可以像这样

在 json 中组合用户名端点中的角色端点及其给出的响应
{
  username:'femix',
  role:'admin'
}

它将为您节省 1 个请求,而不是仅仅为了获取用户名和角色而使用 2 个请求。

差不多一年后,我想用答案更新我的问题。

我需要创建一个 ProfileService 实现 IProfileService 接口

public class ProfileService : IProfileService
{
    protected UserManager<ApplicationUser> UserManager;
    public ProfileService(UserManager<ApplicationUser> userManager)
    {
        UserManager = userManager;
    }

    public async Task GetProfileDataAsync(ProfileDataRequestContext context)
    {
        ApplicationUser user = await UserManager.GetUserAsync(context.Subject);

        IList<string> roles = await UserManager.GetRolesAsync(user);

        var claims = new List<Claim> {
            // here you can include other properties such as id, email, address, etc. as part of the jwt claim types
            new Claim(JwtClaimTypes.Email, user.Email),
            new Claim(JwtClaimTypes.Name, $"{user.Firstname} {user.Lastname}")
        };
        foreach (string role in roles)
        {
            // include the roles
            claims.Add(new Claim(JwtClaimTypes.Role, role));
        }

        context.IssuedClaims.AddRange(claims);
    }

    public Task IsActiveAsync(IsActiveContext context)
    {
        return Task.CompletedTask;
    }
}

已将 DI 注册添加到 Startup

services.AddTransient<IProfileService, ProfileService>();