Unable to Retrieve Users from Azure AD in Angular SPA

kunal 0 Reputation points
2024-11-26T10:02:36.3+00:00

I am using work account and authenticating a user through Microsoft Azure AD in my Angular application(SPA). After successfully logging in, I need to fetch all user details from Microsoft AD using the API endpoint: https://graph.microsoft.com/v1.0/users.

To achieve this, I acquire an access token using the acquireTokenSilent method and attempt to include it in the request's Authorization header, as shown in the following code snippet:

getADUsers(): Observable<any> {
    const request = {
      scopes: ['User.Read', 'User.ReadBasic.All', 'User.Read.All', 'Directory.Read.All'],
      account: this.msalService.instance.getActiveAccount()
    };
    return from(this.msalService.acquireTokenSilent(request)).pipe(
      switchMap(tokenResponse => {
        let headers = new HttpHeaders();
          headers = headers.append('authorization', `Bearer ${tokenResponse.accessToken}`)
        return this.http.get('https://graph.microsoft.com/v1.0/users', { headers : headers });
      })
    );
}

I am encountering a 401 Unauthorized error. After inspecting, I found that the Authorization header is missing from the request headers.

When I test the same API using Postman and cURL with the access token, it works successfully and retrieves all users from AD.

I tried to manually set the Authorization header with the token in the HTTP request, but the header still does not appear in the outgoing request. I also implemented an Angular HTTP interceptor to automatically attach the token to the Authorization header, but this resulted in a circular dependency error, which I could not resolve. Additionally, I tried specifying the clientId in the resource map, but that did not help either. Any guidance to address this issue would be greatly appreciated. Thank you!

Microsoft Graph
Microsoft Graph
A Microsoft programmability model that exposes REST APIs and client libraries to access data on Microsoft 365 services.
12,461 questions
Microsoft Entra ID
Microsoft Entra ID
A Microsoft Entra identity service that provides identity management and access control capabilities. Replaces Azure Active Directory.
22,425 questions
0 comments No comments
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.