您如何使用 MSAL-ANGULAR 读取 Roles/Permissions

How do you read Roles/Permissions using MSAL-ANGULAR

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

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

也许我遗漏了什么。如有任何建议,我们将不胜感激

(感谢 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');
      });
  });
}

要获取用户所属的组,您需要将 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
    });
});

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

sample(虽然它是针对 .NET 的)详细解释了这一点

您只需要 User.Read 权限即可使用 memberof v1。 使用 import * as MicrosoftGraph from '@microsoft/microsoft-graph-client';修复 microsoft-graph-client header 导出错误。 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');
    });

}

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

对于现代浏览器,这可以在本地存储中找到,对于 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/ 手动解码数据。

您可以使用 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",