用于React中访问令牌和刷新令牌的Axios拦截器

时间:2019-01-09 23:15:11

标签: javascript html reactjs promise axios

我正在尝试调试访问令牌中的拦截器所遇到的问题,并刷新令牌要求。我尝试遵循Axios interceptors and asynchronous login中的调试过程,也遵循https://shinework.io/post/handle-oauth2-authentication-with-react-and-flux

中的axios拦截器格式和过程。

但是,我似乎无法弄清楚为什么我的应用程序无法正常工作。我是拦截器的新手,我认为这可能与如何弹出拦截器有关?我在axios请求期间遇到了一个问题,我尝试使用从刷新端点收到的更新的访问令牌运行初始请求。我的根index.js文件中有这段代码

当我在访问令牌过期后进行调试时,将使用新的访问令牌呈现初始请求调用的catch块中的'Rejecting'的console.log。再次,目的是利用刷新令牌来获取新的access_token和refresh_token集,然后利用新的access_token进行初始请求调用。

请求和响应拦截器:

axios.interceptors.request.use(
      config => {
        const token = localStorage.getItem('access_token');
        config.headers.authorization = `Bearer ${token}`;
        return config;
      },
      error => {
        return Promise.reject(error);
      },
    );

axios.interceptors.response.use(
      response => {
        return response;
      },
      error => {
        const errorMessage = error.message;
        const substring = '401';
        const errorCheck = errorMessage.includes(substring);

        return new Promise((resolve, reject) => {
          if (errorCheck) {
            onRefreshToken({
              initialRequest: error.config,
              resolve,
              reject,
            });
          } else {
            refreshFailLogout(store);
            reject(error);
          }
        });
      },
    );

onRefreshToken()和saveTokens()

const onRefreshToken = params => {
  let refreshToken = store.getState().auth.refresh_token;
  if (refreshToken) {
    axios.interceptors.request.eject(InterceptorUtil.getInterceptor());

    const dataSet = {
      refresh_token: `${refreshToken}`,
    };
    axios
      .post('https://localhost:3469/api/Login/$refresh', dataSet)
      .then(response => {
        saveTokens(response.data);

        // Replay request
        axios(params.initialRequest)
          .then(response => {
            params.resolve(response);
            store.dispatch({ type: AUTHENTICATED, payload: response.data });
          })
          .catch(response => {
            console.log('Rejecting')
            params.reject(response);
          })
          .catch(() => {
            refreshFailLogout();
          });
      });
  }
};

const saveTokens = response => {
  const {
    access_token,
    refresh_token,
    scope,
    id_token,
    token_type,
  } = response;

  // ...local storage save of variables
  let token = localStorage.getItem('access_token');

  let interceptor = axios.interceptors.request.use(config => {
    config.headers.authorization = `Bearer ${token}`;
    return config;
  });

  InterceptorUtil.setInterceptor(interceptor);
};

InterceptorUtil类

class InterceptorUtil {
  constuctor() {
    this.interceptor = null;
  }

  setInterceptor(interceptor) {
    this.interceptor = interceptor;
  }

  getInterceptor() {
    return this.interceptor;
  }
}

export default new InterceptorUtil();

0 个答案:

没有答案