应用程序不使用 MSAL (react-aad-msal) 从缓存中获取访问令牌

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

authProvider.getAccessToken() 为每个 API 调用调用身份验证端点,而不是从缓存中获取它。

我不知道问题出在 Msal 中的 AcquireTokenSilent 还是 react-aad-msal 中的 getAccessToken。

使用 msal 1.2.1 和 react-aad-msal 2.3.2

Api呼叫助手:

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

配置:

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

我遇到了同样的问题,请尝试将所需的范围添加到访问令牌请求中。

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

我通过从范围中删除 'offline_access' 解决了这个问题,因为它似乎是隐式添加的,手动添加它会导致 MSAL 找不到缓存的令牌,因为范围用作键。

我还必须添加我的自定义范围,在我的例子中 'User.Read'

const authenticationParameters = {
  scopes: ['User.Read'],
};
  const tokenResponse = await MsalInstance.acquireTokenSilent({
        scopes: ['User.read', 'whatyouwant','whatyouneed','whatyoudeepdesire'],
        account: MsalInstance.getAccountByUsername(username) , // or MsalInstance.getAllAccounts()[0].username
        forceRefresh: true
    }).then(data=>{
      if (data.idTokenClaims) {
           console.log(data.idTokenClaims.exp)
        }
    })