1
votes

authProvider.getAccessToken() calls the authentication endpoint for every API call, instead of fetching it from the cache.

I don't know if the issue is with AcquireTokenSilent in Msal or getAccessToken in react-aad-msal.

Using msal 1.2.1 and react-aad-msal 2.3.2

Network

Api call helper:

import { config } from '../config';
import { authProvider } from './../authProvider';

export const callApi = async (method: 'GET' | 'POST' | 'PUT' | 'DELETE', path: string, data?: any) => {
  const token = await authProvider.getAccessToken();

  const res = await fetch(`${config.API_ENDPOINT}/api/${path}`, {
    method,
    headers: {
      Authorization: 'Bearer ' + token.accessToken,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(data),
  });

  return res.json();
};

Config:

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

// Msal Configurations
const config = {
  auth: {
    authority: 'https://login.microsoftonline.com/<my tenant id>',
    clientId: '<my client id>',
  },
  cache: {
    cacheLocation: 'localStorage',
    storeAuthStateInCookie: false,
  },
};

// Authentication Parameters
const authenticationParameters = {
  scopes: ['offline_access'],
};

// Options
const options = {
  loginType: LoginType.Redirect,
  tokenRefreshUri: window.location.origin + '/auth.html',
};

export const authProvider = new MsalAuthProvider(config, authenticationParameters, options);
2

2 Answers

1
votes

I stumbled to the same issue, try to add the required scope to the access token request.

const token = await authProvider.getAccessToken({
  scopes: ['offline_access']
});
0
votes

I fixed the problem by removing 'offline_access' from scopes, as it seems it's added implicitially, and adding it manually causes MSAL to not find the cached token as the scopes are used as key.

I had to add my custom scopes as well, in my case 'User.Read'

const authenticationParameters = {
  scopes: ['User.Read'],
};