angularazure-active-directorymsal-angular

accessing generated access token when using msal


I am having an angular webapp to access protected WebApis. I have created 2 Azure AD apps - one for SPA and another for Webapi. I am using msal v3 for implementing authentication of users. The authentication works fine and the access token obtained for the user is attached by the msal interceptor on making every request to the protected Webapis. I want to access the access token programmatically, how can I do that? Does msal provide any method do so?


Solution

  • You should be able to simply inject MsalService in any component or service in your app.

    First or all, you're going to need to import MSAL modules with:

    import { MsalService } from '@azure/msal-angular'
    import { AuthenticationResult } from '@azure/msal-browser'
    

    Then, you simply inject MsalService in your constructor:

    constructor(private msalService: MsalService) {}
    

    Finally, you'll use the acquireTokenSilent method to acquire your token and do whatever you need with it like so:

    this.msalService.instance.acquireTokenSilent({
      scopes: ["api-scopes-you-need"]
    }).then((response: AuthenticationResult) => {
       const acquiredToken = response.accessToken;
       // Now it's up to you to do whatever you like with the token here...
    )}.catch(error => {
       // Handle errors fetching the token here...
    });
    

    You can checkout MSAL documentation here. The docs also delve into the actual method of acquiring the token, which is initially returned from cache if available, or, if not available, a refresh token is requested.