2022-03-29

React MSAL not working after page refresh

I am using @azure/msal-react and @azure/msal-browser for authentication in our application. So far i have intialized a msal instance and used it to acquire a token and fetch the alias. Everything works until i do a page refresh i want to understand if this is a cache issue i see data is present in local storage regarding msal but still getting null in active account.

here you can see the msal instance with configuration (authProvider) AuthProvider.js

import * as APIConstants from "./Common/APIConstants";

import {
  BrowserCacheLocation,
  PublicClientApplication,
  LogLevel
} from '@azure/msal-browser';

const loggerCallback = (logLevel, message) => {
  console.log(message);
};

const configuration = {
  auth: {
    authority: APIConstants.TENANT,
    clientId: APIConstants.CLIENT_ID,
    postLogoutRedirectUri: window.location.origin,
    redirectUri: window.location.origin,
    validateAuthority: true,
    navigateToLoginRequestUrl: true,
  },
  cache: {
    cacheLocation: BrowserCacheLocation.localStorage,
    storeAuthStateInCookie: true,
  },

  system: {
    loggerOptions: {
      loggerCallback,
      logLevel: LogLevel.Info,
      piiLoggingEnabled: false
    }
  }
};

export const authProvider = new PublicClientApplication(configuration);

Login.js

import React, { Component } from "react";
import { authProvider } from "../../authProvider";
import * as APIConstants from "../../Common/APIConstants";

import {
  EventType,
} from '@azure/msal-browser';

class Login extends Component {

  constructor() {
    super()
    this.successEventId = null;
  }

  loginSuccessCallback = (event) => {
    if (event.eventType === EventType.LOGIN_SUCCESS && event.payload) {
      const payload = event.payload;
      const account = payload.account;
      authProvider.setActiveAccount(account);
      this.props.history.push("/dashboard");
    }
  }

  componentDidMount = () => {
    this.successEventId = authProvider.addEventCallback(this.loginSuccessCallback);
  }

  componentWillUnmount = () => {
    if (this.successEventId)
      authProvider.removeEventCallback(this.successEventId);
  }

  onLDAPLogin = () => {
    authProvider.loginRedirect({
      scopes: [APIConstants.RESOURCE_URI],
    })
  }



  render() {
    return (
      < div >
        <button onClick={() => this.onLDAPLogin()}>LDAP Login</button>
      </div>
    );
  }
}
export default Login;

dashboard.js

purpose dashboard.js is to collect data through api call where you use alias and token of that user to make the call

const getAllData = async () => {
                let user = await Services.getLogedInUser();
                if (user) {
                    let username = user.username;
                    let alias = username.split("@")[0];
                    let token = await Services.getAccessToken();
                    if (token) {
                        await initiateApiCall(alias,token);
                    } else {
                        props.history.push("/");
                    }
                }
                else {
                    props.history.push("/");
                }

}

Services.js

export const getAccessToken = async () => {
  const activeAccount = authProvider.getActiveAccount();
  const accounts = authProvider.getAllAccounts();

  if (!activeAccount && accounts.length === 0) {
    /*
    * User is not signed in. Throw error or wait for user to login.
    * Do not attempt to log a user in outside of the context of MsalProvider
    */
  }
  const request = {
    scopes: [APIConstants.RESOURCE_URI],
    account: activeAccount || accounts[0]
  };

  const authResult = await authProvider.acquireTokenSilent(request);

  console.log('auth result acquire token ', authResult);
  return authResult.accessToken
};

export const getLogedInUser = async () => {
  console.log('authProvider', authProvider);
  console.log('all accounts ', authProvider.getAllAccounts());
  let account = authProvider.getActiveAccount();
  console.log('account ', account);
  return account;
};

As it is shown in the console i get both active account and all accounts value but in case i refresh the page active account is null and all accounts is an empty array



No comments:

Post a Comment