【问题标题】:How to get user role on client side?如何在客户端获取用户角色?
【发布时间】:2020-08-25 21:46:42
【问题描述】:

我正在开发带有 ASP.NET Core 后端的 Angular Web 应用程序。从用于个人用户帐户身份验证的内置“带有 Angular 的 ASP.NET Core 应用程序”模板项目开始。我的问题是在客户端获取经过身份验证的用户角色(我想在角色中处理警卫和菜单)。

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

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

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

还有其他解决方案吗?

我尝试了另一种解决方案,但效果不佳。 在授权服务中,当在登录期间建立用户个人资料(可以是任何个人资料)时,我应该将角色附加到个人资料。

感谢您的建议

【问题讨论】:

  • 登录时不能用配置文件服务器端返回角色吗?

标签: angular asp.net-core openid-connect


【解决方案1】:

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

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

你应该这样做:

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】:

    如果您有权使用后端代码,最好将 2 个端点合二为一,... 例如。您可以在用户名端点中结合角色端点及其在 json 中的响应,如下所示

    {
      username:'femix',
      role:'admin'
    }
    

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

    【讨论】:

      【解决方案3】:

      将近一年后,我想用答案更新我的问题。

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

      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;
          }
      }
      

      在 Startup 中添加了 DI 注册

      services.AddTransient<IProfileService, ProfileService>();
      

      【讨论】:

        猜你喜欢
        • 2020-09-19
        • 2019-06-16
        • 2021-11-01
        • 2018-08-20
        • 1970-01-01
        • 1970-01-01
        • 2013-01-14
        • 1970-01-01
        • 2016-12-03
        相关资源
        最近更新 更多