应用程序不使用MSAL(react-aad-msal)从缓存中获取访问令牌 [英] Application does not fetch access token from cache using MSAL (react-aad-msal)

查看:224
本文介绍了应用程序不使用MSAL(react-aad-msal)从缓存中获取访问令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

使用msal 1.2.1和react-aad-msal 2.3.2

Using msal 1.2.1 and 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);

推荐答案

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

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.

我还必须添加自定义范围,在我的情况下为"User.Read"

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

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

这篇关于应用程序不使用MSAL(react-aad-msal)从缓存中获取访问令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆