0

我添加了一个 axios 拦截器,在其中调用 authProvider.getAccessToken() 来获取令牌并添加到每个请求的标头中。

这是我的 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)
})

这是我的 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 在 App.js 中使用

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

....

</AzureAD>

axiosInterceptor 也包含在 App.js 中。

请就可能导致组件无限重新加载的原因提供建议。我已删除 authProvider.getAccessToken() 并验证,它工作正常。所以重载是由于这个原因引起的。

4

1 回答 1

0

首先,我建议您验证 AuthProvider 的 Scope、authority 和 clientId。

我在一个项目中遇到了类似的问题,我必须将范围添加到 getAccessToken() 函数,即使我从未在其他项目中这样做过。

见下文:

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

希望它有所帮助;)问候

于 2021-04-21T11:35:36.577 回答