但无论是否使用refreshToken

但无论是否使用refreshToken

本文介绍了调用了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.

推荐答案

通常流应该是这样的:

  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和获取令牌,令牌都已过期.整理所有API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 16:46