【问题标题】:react-aad-msal authProvider.getAccessToken() reloads the component indefinitelyreact-aad-msal authProvider.getAccessToken() 无限期重新加载组件
【发布时间】:2021-07-05 08:41:36
【问题描述】:

我添加了一个 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() 并验证,它工作正常。所以重载就是因为这个原因。

【问题讨论】:

    标签: reactjs azure-active-directory react-aad-msal


    【解决方案1】:

    首先,建议你验证一下你的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);
              });
          });
        });
    

    希望对您有所帮助;) 问候

    【讨论】:

      猜你喜欢
      • 2020-06-02
      • 2022-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      • 2020-07-10
      相关资源
      最近更新 更多