Unable to acquire token silently or via redirect using msal-browser

Had to go through some trial and error but finally got acquireTokenRedirect working successfully, this is the excerpt which may help others:

import * as Msal from '@azure/msal-browser';

const msalConfig = {
  auth: {
    clientId:    "XYZ",
    authority:   "ABC",
  },
  cache: {
    cacheLocation: 'localStorage',
    storeAuthStateInCookie: true
  }
};

export default class AuthenticationService {

  constructor() {

    this.app = new Msal.PublicClientApplication(msalConfig)
  }

  init = async () => {

    try {
      let tokenResponse = await this.app.handleRedirectPromise();

      let accountObj;
      if (tokenResponse) {
        accountObj = tokenResponse.account;
      } else {
        accountObj = this.app.getAllAccounts()[0];
      }

      if (accountObj && tokenResponse) {
        console.log("[AuthService.init] Got valid accountObj and tokenResponse")
      } else if (accountObj) {
        console.log("[AuthService.init] User has logged in, but no tokens.");
        try {
          tokenResponse = await this.app.acquireTokenSilent({
            account: this.app.getAllAccounts()[0],
            scopes: ["user.read"]
          })
        } catch(err) {
          await this.app.acquireTokenRedirect({scopes: ["user.read"]});
        }
      } else {
        console.log("[AuthService.init] No accountObject or tokenResponse present. User must now login.");
        await this.app.loginRedirect({scopes: ["user.read"]})
      }
    } catch (error) {
      console.error("[AuthService.init] Failed to handleRedirectPromise()", error)
    }

  }

}

Tags:

Adal

Msal

Msal.Js