How do you read Roles/Permissions using MSAL-ANGULAR

℡╲_俬逩灬. 提交于 2020-01-25 00:25:07

问题


So I've successfully integrated Azure AD authentication in my angular site as per the instructions in msal-angular and now I'm at the point where I'm looking to define and leverage roles and permissions to provide more granular control of what a user can and can't do.

From what I've been able to determine I can define roles by following this set of instructions (https://docs.microsoft.com/en-us/azure/architecture/multitenant-identity/app-roles) but msal-angular doesn't seem to expose this upon logging in - or at least I haven't found instructions on how to do this just yet.

Perhaps I'm missing something. Any suggestions would be appreciated


回答1:


To get the groups a user belongs to, you will need to add directory.read.all to your scope in your Angular app and also in the API permissions in the Azure app settings.

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



回答2:


You can change the manifest to get these delivered in the token itself.

The sample (its for .NET though), explains this in detail




回答3:


(Thanks goes to stillatmylinux)

FYI: Here's my working angular 7 solution (simplified for the sake of readability):

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


来源:https://stackoverflow.com/questions/56041125/how-do-you-read-roles-permissions-using-msal-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!