简体   繁体   English

Axios 用于令牌刷新的全局拦截器

[英]Axios global interceptor for token refresh

OK, so this is my third wall I'm hitting with this problem, first off here's my axios config file好的,这是我遇到这个问题的第三面墙,首先这是我的 axios 配置文件

import axios from "axios";
import { withRouter } from "react-router-dom";

const instance = axios.create({
  baseURL: process.env.REACT_APP_API,
  headers: {
    "content-type": "application/json"
  },
  responseType: "json"
});
function pushToLogin() {
  this.props.history.push("/");
}
function createAxiosResponseInterceptor(axiosInstance) {
  const interceptor = axiosInstance.interceptors.response.use(
    response => response,
    error => {
      // Reject promise if usual error
      console.log(error);
      if (error.response.status !== 401) {
        return Promise.reject(error);
      }
      /*
       * When response code is 401, try to refresh the token.
       * Eject the interceptor so it doesn't loop in case
       * token refresh causes the 401 response
       */
      axiosInstance.interceptors.response.eject(interceptor);
      return axiosInstance
        .post("token/refresh/", {
          refresh: localStorage.getItem("refreshToken")
        })
        .then(response => {
          localStorage.setItem("accessToken", response.data.access);
          error.response.config.headers["Authorization"] =
            "Bearer " + response.data.access;
          return axiosInstance(error.response.config);
        })
        .catch(error => {
          localStorage.setItem("accessToken", null);
          localStorage.setItem("refreshToken", null);
          pushToLogin();
          return Promise.reject(error);
        })
        .finally(createAxiosResponseInterceptor(this));
    }
  );
}

createAxiosResponseInterceptor(instance);

export default withRouter(instance);

What I want, is: Request gets 401 > Get a new token and store it > repeat request > if it's good to go we're good, if not return it's normal error.我想要的是:请求获取 401 > 获取一个新令牌并存储它 > 重复请求 > 如果它对 go 有好处,我们很好,如果没有返回它是正常错误。

What's happening: Request gets 401 > Gets new token and stores it > Repeat request> if it's good we're good to go, if not, it goes into that final catch block on my interceptor, which I thought was intended specifically for the refreshToken request, or atleast that's what I desire it to be.发生了什么:请求获取 401 > 获取新令牌并存储它 > 重复请求 > 如果它很好,我们对 go 很好,如果不是,它进入我的拦截器上的最后一个 catch 块,我认为它是专门用于 refreshToken请求,或者至少这是我想要的。

Bonus question: I'd like to push to login on refreshToken failure as u can see, I'm trying to use withRouter for that but I cannot read props of undefined on that push line, so that's another issue.奖励问题:如您所见,我想在 refreshToken 失败时推送登录,我正在尝试使用 withRouter ,但我cannot read props of undefined ,所以这是另一个问题。

Many thanks!非常感谢!

Edit:Even if this request has been done by other ways I'd like to know what's wrong with my code than learn someone else's.编辑:即使这个请求是通过其他方式完成的,我也想知道我的代码有什么问题,而不是学习别人的代码。

I switched to using the axios-auth-refresh package, the config code I'm using is here:我切换到使用axios-auth-refresh package,我使用的配置代码在这里:

import axios from "axios";
import createAuthRefreshInterceptor from "axios-auth-refresh";

const instance = axios.create({
  baseURL: process.env.REACT_APP_API,
  headers: {
    "content-type": "application/json"
  },
  responseType: "json"
});
const refreshAuthLogic = failedRequest =>
  instance
    .post("token/refresh/", {
      refresh: localStorage.getItem("refreshToken")
    })
    .then(tokenRefreshResponse => {
      localStorage.setItem("accessToken", tokenRefreshResponse.data.access);
      failedRequest.response.config.headers["Authorization"] =
        "Bearer " + tokenRefreshResponse.data.access;
      return Promise.resolve();
    })
    .catch(error => {
      console.log("refresh fail");
      localStorage.setItem("accessToken", null);
      localStorage.setItem("refreshToken", null);
      //pushToLogin();
      return Promise.reject(error);
    });
createAuthRefreshInterceptor(instance, refreshAuthLogic);

export default instance;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM