3

I am working on an Angular 8 application that is trying to retrieve list of all the Microsoft AD groups available to the logged in user. Previously, I was working on authenticating a user using MSAL library and was successfully able to get the following values:

  • access token
  • idToken
  • homeIdentifier
  • expiresIn

My MSAL configuration is as under:

export function MSALAngularConfigFactory(): MsalAngularConfiguration {
  var isIE = window.navigator.userAgent.indexOf("MSIE ") > -1 ||
    window.navigator.userAgent.indexOf("Trident/") > -1;
  return {
    popUp: !isIE,
    consentScopes: [
      'user.read',
      'openid',
      'profile',
      'group.Read.All'
    ],
    unprotectedResources: ['https://www.microsoft.com/en-us/'],
    protectedResourceMap: [
      ['https://graph.microsoft.com/v1.0/me', ['user.read']],
      ['https://graph.microsoft.com/v1.0/groups', ['group.read.all']]
    ]
  };
}
export function MSALConfigFactory(): Configuration {
  var isIE = window.navigator.userAgent.indexOf("MSIE ") > -1 ||
    window.navigator.userAgent.indexOf("Trident/") > -1;
  return {
    auth: {
      clientId: environment.clientId,
      authority: environment.authority,
      validateAuthority: true,
      redirectUri: environment.redirectUrl,
      postLogoutRedirectUri: environment.redirectUrl,
      navigateToLoginRequestUrl: true,
    },
    cache: {
      cacheLocation: 'localStorage',
      storeAuthStateInCookie: isIE,
    }
  };
}

When I call getAccount().idTokenClaims['groups'] method of MSAL, it returns me the array of groups with just some identifier values which is not my requirement. I need an array of AD group names.

I implemented MicrosoftGraph Library too for getting groups using the following API:

fetch('https://graph.microsoft.com/v1.0/groups', {
     headers: {
         'Authorization': 'Bearer ' + {access_token},
         'Content-Type': 'application/json',
     }
 }).then(res => { console.log(res); });

The above code always results in error stating : 401 (Unauthorized)

I have tried multiple solutions from Microsoft Graph including the following:

const msalConfig = {
      auth: {
        clientId: clientId, // Client Id of the registered application
        redirectUri: "https://localhost:4200",
      }
 };
 const graphScopes = ["user.read", "group.read.all"]; // An array of graph scopes
 const msalApplication = new UserAgentApplication(msalConfig);
 const options = new MSALAuthenticationProviderOptions(graphScopes);
 const authProvider = new ImplicitMSALAuthenticationProvider(msalApplication, options);

 this.subscription1 = broadcast.subscribe("msal:loginSuccess",
      (result) => {
        //The result has accessToken as null.
        fetch('https://graph.microsoft.com/v1.0/groups', {
          headers: {
            'Authorization': 'Bearer ' + {accessToken},
            'Content-Type': 'application/json',
          }
        }).then(response => { console.log(response);});

The above code snippet returns an error too stating that :

CompactToken parsing failed with error code: 80049217

I have tried a few more solutions but nothing worked for me. I am stuck in it from yesterday.

Can someone help me find out what can be the best solution for it. Any help will be highly appreciated.

Thanks in advance.

megha
  • 141
  • 2
  • 15
  • Looks like the main issue is the access token is invalid. How do you get it? Decode it in https://jwt.io and you can see the details of it. – Allen Wu Jan 13 '21 at 02:33
  • Hi @AllenWu. Thanks for the observation. It actually was the problem with my accessToken. The method that I was using did not return any accessToken. Another method that I used was working on expired token. jwt.io is a very simple and elegant way to check your token status. – megha Jan 13 '21 at 15:34

1 Answers1

1

Not quite sure about the context of your application. My code demo is based on this official Angular MSAL demo.

After you have configured this app correctly at src/app/app.module.ts, go to src/profile/profile.component.ts add the function below to get all group names:

  getAccessTokenAndCallGraphAPI(){

    this.authService.acquireTokenSilent({
      scopes: ['group.Read.All']
    }).then(result=>{
      const httpOptions = {
        headers: new HttpHeaders({
          'Content-Type':  'application/json',
          Authorization: 'Bearer '+result.accessToken
        })}

      this.http.get("https://graph.microsoft.com/v1.0/groups?$select=id,displayName",httpOptions).toPromise().then(result=>{console.log(result)});
    })
  }

Call this function on page init:

 ngOnInit() {
    this.getProfile();
    this.getAccessTokenAndCallGraphAPI();
  }

Result: Access "profile" page will print all IDs and names of groups in the console. enter image description here enter image description here

Please make sure that you have granted your application with permission below before you call this API: enter image description here

Stanley Gong
  • 11,522
  • 1
  • 8
  • 16
  • Thanks alot for the response. It worked like a charm. I was trying to create an instance of userApplicationAgent, AuthenticationProvider to pass as parameters to acquireTokenSilent looking at some documentation and also calling fetch method to get data groups using graph. But it was resulting in empty accessToken. But this code worked flawlessly. I have another problem similar to that. I will come up with that too in a little while. I am sure I will get a detailed and correct explanation to that too. Thanks again. – megha Jan 13 '21 at 15:24