Unable to Retrieve Users from Azure AD in Angular SPA
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!