Application does not fetch access token from cache using MSAL (react-aad-msal)

谁说我不能喝 提交于 2020-04-30 11:43:21

问题


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

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);

回答1:


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']
});



回答2:


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'],
};


来源:https://stackoverflow.com/questions/59789433/application-does-not-fetch-access-token-from-cache-using-msal-react-aad-msal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!