Unable to Attach Access Token from acquireTokenSilent in Angular to HTTP Requests for...

Discussão em 'Angular' iniciado por zero_one, Novembro 26, 2024.

  1. zero_one

    zero_one Guest

    Creating new question as available solutions from other questions did not resolve my issue.

    I am authenticating a user through Microsoft Azure AD in my Angular application. 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:

    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. Also, I tried specifying the clientId in resourcemap did not help me as well. Any guidance to address this issue would be greatly appreciated. Thank you!

    Continue reading...

Compartilhe esta Página