Axios 拦截器响应令牌刷新 API 调用但获取令牌已过期,无论在 refreshToken API &对所有 API 进行编译 [英] Axios Interceptor Response Token Refresh API called but getting Token is expired regardless in refreshToken API & lator all APIs

查看:16
本文介绍了Axios 拦截器响应令牌刷新 API 调用但获取令牌已过期,无论在 refreshToken API &对所有 API 进行编译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 axios 拦截器是:-

my axios interceptor is:-

axios.interceptors.response.use((response, error) => {
  const originalRequest = response.config;

  if (response.data.status === 'Token is Expired' && originalRequest.url === '/api/refresh') {
    this.props.history.push('/logout');
    Promise.reject(error);
  }

  if (response.data.status === 'Token is Expired' && !originalRequest._retry) {
    originalRequest._retry = true;
    const playerToken = localStorage.getItem('accessToken');
    return axios
      .get('/api/refresh', {
        headers: {
          Authorization: `bearer ${playerToken}`,
        },
      })
      .then(res => {
        console.log('from refreshtoken', res);
        const stringRes = JSON.stringify(res);
        const parsedRes = JSON.parse(stringRes);
        const stringData = JSON.stringify(parsedRes.data);
        const parsedData = JSON.parse(stringData);
        const stringToken = JSON.stringify(parsedData.data);
        const parsedToken = JSON.parse(stringToken);

        if (parsedData.success == true) {
          localStorage.setItem('accessToken', playerToken);
          axios.response.config.headers['Authorization'] = `bearer ${parsedToken}`;
          return Promise.resolve();

          return axios(originalRequest);
        } else {
          this.props.history.push('/logout');
        }
      })
      .catch(err => {
        console.log('from refreshtoken', err);
      });
  }

  return Promise.reject(error);
});

我的代码正在运行,但是当我第一次调用我的刷新令牌 API 时,它还返回相同的状态令牌已过期",因为我已退出应用程序.这仅发生在拦截器中.当我在拦截器之外调用 Refresh API 时,它会返回一个刷新令牌.

My code is running but when my refresh token API is called first time, It also returns the same status "Token is expired" due to which i am logged out of the app. This is happening only in interceptor. When i am calling Refresh API outside of interceptor, it returns with a refresh token.

我的代码有错误吗?或者完全是其他一些编码错误.请回答&告诉我正确的做法&我在哪里放置我的拦截器?目前它被放置在一个在登录后立即调用的组件中.

Does my code have mistakes? or it is some other coding fault entirely. Please answer & tell me the right way to do it & where do i place my interceptor?? Currently it is placed in a Component which is called just after login.

推荐答案

通常流程应该是这样的:

Usually the flow should be as such:

  1. 使用 accessToken
  2. 发出常规请求
  3. 请求失败,状态码为 401
  4. axios 拦截器捕获它并向 token/refresh 发出请求.它从该响应中获得一个新的访问令牌.
  5. 重试原始请求.
  1. making a regular request with accessToken
  2. request fails with status code 401
  3. axios interceptor catches it and makes request to token/refresh. from that response it gets a new access token.
  4. retries the original request.

所以代码应该是这样的(这是我的应用程序的一个工作示例):

So the code should looks like this (this is a working example from my app):

function isUnAuthorizedError(error) {
  return error.config && error.response && error.response.status === 401;
}

function shouldRetry(config) {
  return config.retries.count < 3;
}

function updateAuthToken(response) {
  localStorage.setItem('token', response.data.accessToken);
}

async function authInterceptor(error) {
  error.config.retries = error.config.retries || {
    count: 0,
  };

  if (isUnAuthorizedError(error) && shouldRetry(error.config)) {
    const response = await axios.post(`/token/refresh`, {});

    updateAuthToken(response);

    error.config.retries.count += 1;
    axios.defaults.headers.common.Authorization = `Bearer ${response.data.accessToken}`; // update the accessToken
    return axios.rawRequest(error.config); // retries the original request
  }
  return Promise.reject(error);
}

axios.interceptors.response.use(null, authInterceptor); // This indicates that authInterceptor will work only on request errors (status code >= 400)

希望这个流程更有意义.

Hopes this flow makes more sense.

这篇关于Axios 拦截器响应令牌刷新 API 调用但获取令牌已过期,无论在 refreshToken API &amp;对所有 API 进行编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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