Thuy
Thuy

Reputation: 1665

How to get access token with MSAL

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.

Upvotes: 7

Views: 44526

Answers (2)

Cinosarge
Cinosarge

Reputation: 11

Approach 1

Only works if you actually do a redirect: next time, once logged in, you won't get your console message.

Based on this guide (https://learn.microsoft.com/en-us/azure/active-directory/develop/scenario-spa-acquire-token?tabs=javascript2) I came up with the following

this.msalsrv.handleRedirectObservable().subscribe( (redirectResponse) => {
  if(redirectResponse != null) {
    // Acquire token silent success
    let accessToken = redirectResponse.accessToken;
    // Call your API with token
    console.log("We got the token! hahaha: " + accessToken);
  }
})

Approach 2

Made another try and figured out how to get the token. Make sure to use this code once the login processed has alredy been perfomed (for example if you're a page under MsalGuard).

const accessTokenRequest = {
  scopes: ["user.read"],
  account: this.msalsrv.instance.getAllAccounts()[0],
};


this.msalsrv.acquireTokenSilent(accessTokenRequest).subscribe( (accessTokenReponse) => {
  if(accessTokenReponse != null) {
    // Acquire token silent success
    let accessToken = accessTokenReponse.accessToken;
    // Call your API with token
    console.log("We got the token! hahaha: " + accessToken);
  }
})

Notice this code just works.. you have to ensure what happens if your session has expired.

Upvotes: 0

Thuy
Thuy

Reputation: 1665

  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://learn.microsoft.com/en-us/azure/active-directory/develop/msal-acquire-cache-tokens

Azure/Msal authentication inside PowerApp Component Framework returns AADSTS50177 error

Upvotes: 7

Related Questions