【问题标题】:How do you read Roles/Permissions using MSAL-ANGULAR您如何使用 MSAL-ANGULAR 阅读角色/权限
【发布时间】:2019-09-26 05:02:25
【问题描述】:

因此,我已按照 msal-angular 中的说明成功地将 Azure AD 身份验证集成到我的 Angular 站点中,现在我正在寻找定义和利用角色和权限来提供更精细的控制用户能做什么和不能做什么。

据我所知,我可以通过遵循这组指令 (https://docs.microsoft.com/en-us/azure/architecture/multitenant-identity/app-roles) 来定义角色,但 msal-angular 似乎在登录时并未公开这一点 - 或者至少我没有找到有关如何执行此操作的说明。

也许我错过了什么。任何建议将不胜感激

【问题讨论】:

    标签: angular permissions azure-active-directory roles msal


    【解决方案1】:

    要获取用户所属的组,您需要将 directory.read.all 添加到 Angular 应用程序的范围以及 Azure 应用程序设置的 API 权限中。

    let graphUser = await graphClient.api('/me').get();
    let graphUserGroups = await graphClient.api(`/users/${graphUser.id}/memberOf`).get();
    
    let user = new User();
    user.id = graphUser.id;
    user.displayName = graphUser.displayName;
    // Prefer the mail property, but fall back to userPrincipalName
    user.email = graphUser.mail || graphUser.userPrincipalName;
    
    graphUserGroups.value.forEach(group => {
        user.groups.push({
            group_id: group.id,
            group_name: group.displayName
        });
    });
    

    【讨论】:

    • 谢谢 - 这就是我所走的道路。您对如何绕过与 directory.read.all 权限相关的“需要管理员同意”提示有任何提示吗?我一直在努力解决这个问题,但还没有找到让管理员同意工作的解决方案
    • 在我的情况下,我必须要求我的帐户管理员授予该权限。
    • 啊,是的——这也是我的发现。谢谢
    【解决方案2】:

    您可以更改清单以在令牌本身中传递这些内容。

    sample(虽然它适用于 .NET),详细解释了这一点

    【讨论】:

    • 我们已经尝试设置appRoles,并且还通过了由tenantId组成的权限url。此外,我们还获得了 Directory.Read.All 的管理员同意,但仍然没有在 idToken 中获取角色/组。知道是否需要更多内容吗?
    • @PavanKumarKattamuri 您需要将authority 设置为https://login.microsoftonline.com/<your azure tenant id>。大多数示例附带的权限使用https://login.microsoftonline.com/common,它不返回组或角色。
    【解决方案3】:

    (感谢 stillatmylinux)

    仅供参考:这是我的工作 angular 7 解决方案(为便于阅读而简化):

    import { MsalService, BroadcastService } from '@azure/msal-angular';
    import { Client } from '@microsoft/microsoft-graph-client';
    
    private subscription: Subscription;
    private graphClient: Client;
    private memberRoles: any[];
    
    constructor(
      readonly auth: MsalService,
      readonly broadcast: BroadcastService
    ) {
      // Initialize Microsoft Graph client
      this.graphClient = Client.init({
        authProvider: async (done) => {
          let token = await this.auth.acquireTokenSilent(["User.Read", "Directory.Read.All"])
            .catch((reason) => {
              done(reason, null);
            });
    
          if (token) {
            done(null, token);
          } else {
            done("Could not get an access token", null);
          }
        }
      });
    
      this.subscription = broadcast.subscribe("msal:loginSuccess",
        () => {
          //Get associated member roles
          this.graphClient.api('/me/memberOf').get()
            .then((response) => {
              this.memberRoles = response.value;
            }, (error) => {
              console.log('getMemberRoles() - error');
          });
      });
    }
    

    【讨论】:

      【解决方案4】:

      您只需要 User.Read 权限并使用 memberof v1。 使用 import * as MicrosoftGraph from '@microsoft/microsoft-graph-client';修复 microsoft-graph-client 标头导出​​错误。 uniqueId 是您的 AzureAD 用户 ID。

      private loginSuccess(uniqueId: string) {
           console.log('LOGIN SUCCESS ', uniqueId);
           (this.graphClient = MicrosoftGraph.Client.init({
            authProvider: async (done) => {
              let param: AuthenticationParameters = { authority:"https://login.microsoftonline.com/{TenantId}",
                                                    scopes:["User.Read"]
                            };
              let response = await this.authService.acquireTokenSilent(param)
              .catch((reason) => {
                done(reason, null);
                });
      
              if (response) {
                done(null, response.accessToken);
              } else {
                done("Could not get an access token", null);
              }
            }
          })).api(`/users/${uniqueId}/memberOf`).get()
          .then((response)=>{
              this.groups = response.value;
              console.log("members ok", this.groups);
          },
          (error)=>{
            console.error('memberOf error');
          });
      
      }
      

      【讨论】:

        【解决方案5】:

        使用 MSAL-ANGULAR(当前稳定版本"@azure/msal-angular": "^1.1.2) 您可以从身份验证响应中访问roles(密钥msal.idtoken)。

        对于现代浏览器,可以在本地存储中找到它,而对于 IE,这将存储在 cookie 中。 由于msal.idtoken 是Jwt,解码它应该提供用户的角色。

        const token = localStorage.getItem('msal.idtoken');
        const payload = jwt_decode(token); // jwt_decode npm package will help you to decode the payload.
        console.log(payload);
        

        您甚至可以使用https://jwt.io/ 手动解码数据。

        【讨论】:

          【解决方案6】:

          您可以使用 MsalService 读取在 Azure 应用注册中定义并在企业应用程序中分配的用户角色:

          let allAccounts = this.msalService.instance.getAllAccounts();
          if (allAccounts.length > 0) {
            let account = allAccounts[0];
            let roles = account.idTokenClaims.roles;
          }
          

          MSAL Angular 版本:

          "@azure/msal-angular": "^2.0.5",
          "@azure/msal-browser": "^2.19.0",
          

          【讨论】:

            猜你喜欢
            • 2018-03-17
            • 2020-04-01
            • 1970-01-01
            • 2017-02-06
            • 2020-04-10
            • 1970-01-01
            • 2017-11-22
            • 2020-09-12
            • 2021-01-17
            相关资源
            最近更新 更多