Search code examples
angularazureazure-api-managementazure-ad-msal

Get Authorization token to call API


I'm trying to call the API that I created by following these directions, I got to the point where I can call the API from Developer Portal using the JWT token.

Now I'm confused, how will the angular client app get this JWT token in order to call the API?

Currently, users of the angular app are in the Active Directory (same AD that was used in directions to set up the API). The sign-in process is done through MSAL library. When I try to get the token by calling acquireTokenSilent and try to call the API using this token, I get 401 error.

How do I get the correct JTW token from the angular app?

enter image description here


Solution

  • Make sure you grant permissions for your client app with the permissions you exposed in the api app, follow this doc.

    Then in the consentScopes , use the api scope of your api, you can find the Application ID URL in the Expose an API page of your API App, e.g. something like api://xxxxxxxxxxxxxxx/api_usage

    consentScopes: [
            '<Application ID URL>/scope'
          ],
    

    When you get the token, use ["<Application ID URL>/scope"] for the scopes.

    const requestObj = {
        scopes: ["<Application ID URL>/scope"]
    };
    
    this.authService.acquireTokenSilent(requestObj).then(function (tokenResponse) {
        // Callback code here
        console.log(tokenResponse.accessToken);
    }).catch(function (error) {
        console.log(error);
    });
    

    Fore more details, refer to Tutorial: Sign in users and call the Microsoft Graph API from an Angular single-page application. In this doc, it calls the MS Graph, to call your own api, change the scopes and it should work.