How to get access token with MSAL

Viewed 7547

I stitched together a lot of tutorials and documentation in order to get an access token with MSALin my JavaScript code. Here are the results of my research.

1 Answers
  1. npm install @azure/msal

  2. import the necessary class from @azure/msal

        import {
          UserAgentApplication,
          AuthenticationParameters,
          Configuration,
        } from "@azure/msal";
    
    
  3. Make the msal object

      const config: Configuration = {
        auth: {
          clientId: <client id - your app's client id>,
          authority: `https://login.microsoftonline.com/<tenantid>`,
          redirectUri: <the redirect Uri>,
        },
      };
    
      const params: AuthenticationParameters = {
        authority: `https://login.microsoftonline.com/${Tenantid}`,
        scopes: [`${AppIDUri}/user_impersonation`],  <-- the API that you're trying to call
      };
    
      const myMSAL = new UserAgentApplication(config);
    
  4. Get access token

     try {
      const login = await myMSAL.acquireTokenSilent(params);
      return login.accessToken;
    } catch (error) {
      await myMSAL.loginPopup(params);
      const login = await myMSAL.acquireTokenSilent(params);
      return login.accessToken;
    }
    

References:

https://docs.microsoft.com/en-us/azure/active-directory/develop/msal-acquire-cache-tokens

Azure/Msal authentication inside PowerApp Component Framework returns AADSTS50177 error

Related