1

I have added a axios interceptor within which authProvider.getAccessToken() is called to fetch token and add to header of each request.

Here is my axiosInterceptor.js

import axios from 'axios'
import { authProvider } from '../authProvider'

export const axiosApiIntance = axios.create()

export const axiosInterceptor = axiosApiIntance.interceptors.request.use(async request => {
    try {
        let token = await authProvider.getAccessToken()
        request.headers['Authorization'] = `Bearer ${token.accessToken}`
        return request
    } catch (err) {
        console.log(err)
    }
}, error => {
    return Promise.reject(error.message)
})

Here is my authProvider.js

import { LoginType, MsalAuthProvider } from 'react-aad-msal'

// The auth provider should be a singleton. Best practice is to only have it ever instantiated once.
// Avoid creating an instance inside the component it will be recreated on each render.
// If two providers are created on the same page it will cause authentication errors.
export const authProvider = new MsalAuthProvider(
  {
    auth: {
      authority: process.env.REACT_APP_AUTHORITY,
      clientId: process.env.REACT_APP_CLIENT_ID,
      postLogoutRedirectUri: process.env.REACT_APP_URL,
      redirectUri: process.env.REACT_APP_URL,
      validateAuthority: true,

      // After being redirected to the "redirectUri" page, should user
      // be redirected back to the Url where their login originated from?
      navigateToLoginRequestUrl: false
    },
    cache: {
      cacheLocation: 'sessionStorage',
      storeAuthStateInCookie: true
    }
  },
  {
    scopes: ['openid', 'profile', 'user.read']
  },
  {
    loginType: LoginType.Redirect,
    // When a token is refreshed it will be done by loading a page in an iframe.
    // Rather than reloading the same page, we can point to an empty html file which will prevent
    // site resources from being loaded twice.
    tokenRefreshUri: window.location.origin + '/auth.html'
  }
)

authProvider is used in App.js

<AzureAD provider={authProvider} reduxStore={configureStore}>

....

</AzureAD>

axiosInterceptor is also included in App.js.

Please provide suggestion on what could cause the component the reload indifinitely. I have removed the authProvider.getAccessToken() and verified, it works fine. So the reload is caused due to that.

Shreyas R
  • 11
  • 2

1 Answers1

0

First, I suggest you to verify the Scope, authority and clientId of your AuthProvider.

I had a similar issue in one project ans I had to add the scope to the getAccessToken() function, even if I never did that in others projects..

See below:

var authenticationParameters = {
  scopes: ['openid', 'profile', 'user.read'],
};

axios.interceptors.request.use(function (config): any {
      return new Promise(async (resolve: any, reject: any) => {
        await authProvider.getAccessToken(authenticationParameters).then((response: any) => {
          config.headers["Authorization"] = "Bearer " + response.accessToken;
          config.headers["Content-Type"] = "application/json";
          config.headers.Accept = "application/json";
          resolve(config);
        })
          .catch((error: any) => {
            console.log(error.message);
          });
      });
    });

Hope it help ;) Regards

G Clovs
  • 2,442
  • 3
  • 19
  • 24