简体   繁体   English

Axios 刷新令牌无限循环 - 多个请求

[英]Axios Refresh Token Infinite Loop - Multiple Requests

I have looked the other questions about this problem but I could not fix it.我查看了有关此问题的其他问题,但无法解决。 I have a get request restriction for the refresh and access token renewal methods and there will be multiple requests in a page.我对刷新和访问令牌续订方法有获取请求限制,并且一个页面中将有多个请求 Furthermore I have a different access-token/refresh token usage in our system.此外,我在我们的系统中使用了不同的访问令牌/刷新令牌

UPDATE: Infinite loop issue is handled by creating an axios instance in the main instance.更新:通过在主实例中创建 axios 实例来处理无限循环问题。 Now, I encounter a request cancellation problem often and couldn't solve it.现在,我经常遇到请求取消问题,无法解决。 After a request, access-token request is made but it is cancelled.请求后,会发出访问令牌请求,但会被取消。 I don't know why.我不知道为什么。

Below you can see the sequence diagrams:下面你可以看到序列图:

Renewing Access Token

Renewing Refresh Token

So far, sometimes it works cursory, a request -> 401 access token expired error -> renew access token in interceptor and write it to localStorage -> same request resolves 200到目前为止,有时它的工作很草率,一个请求 -> 401 访问令牌过期错误 -> 在拦截器中更新访问令牌并将其写入 localStorage -> 相同的请求解析 200

它工作粗略

But most of the time this happens and it continues with 401 loop for access-token:但大多数情况下都会发生这种情况,并且会继续进行访问令牌的 401 循环:

这没用

Note: At the beginning of the access-token loop I get 401 including the "Staff not found" error description which means that in our system the renewed token is not included in the incoming non-token request(expired token is included in header).注意:在访问令牌循环开始时,我得到 401,包括“找不到员工”错误描述,这意味着在我们的系统中,更新的令牌不包含在传入的非令牌请求中(过期的令牌包含在标头中) . Normally the error description of the 401 error for non-token requests is "Token expired".通常非令牌请求的 401 错误的错误描述是“令牌过期”。

Possible noob question: How is it possible to have only one preflight and two xhr for a request?可能的菜鸟问题:一个请求怎么可能只有一个预检和两个 xhr?

Here is my service.js code:这是我的 service.js 代码:

 const sendRequest = async (options) => {
  let requestOptions = {
    ...    // includes the method, data etc.
    if (options.hasOwnProperty("token")) {
        requestOptions.headers = 
          Object.assign(requestOptions.headers, {
          Authorization: RequestOptionConstants.AUTHORIZATION + 
          options.token,
    });
   }
  
 return await axios(
  options.url, //  includes the api url
  requestOptions,    
  axios.interceptors.response.use(
    (response) => {   
      return response;
    },
    async (error) => {
      const originalConfig = error.config;

    if (error.response.status === 401 && !originalConfig._retry) {
      originalConfig._retry = true;

      let refreshToken = JSON.parse(localStorage.getItem("user"))
        .refreshToken;

      // Check for refresh token expiration

      if (jwtDecode(refreshToken).exp < new Date().getTime()) {  
        logout();                  
      }.       

      await axios
        .get(ApiConstants.GET_ACCESS_TOKEN, {
          headers: {
            Authorization:
              "Bearer " +
              JSON.parse(localStorage.getItem("user")).refreshToken,
          },
        })
        .then((res) => {
          if (res.status === 200) {
            const user = JSON.parse(localStorage.getItem("user"));
    

            originalConfig.headers["Authorization"] =
              "Bearer " + res.data.accessToken;

            user.accessToken = res.data.accessToken;

            localStorage.setItem("user", JSON.stringify(user));

            if (res.data.isRefreshTokenInRenewalPeriod) {
              getRefreshToken(originalConfig);
            }

            return axios(originalConfig);
          }
        });
    }

    return Promise.reject(error);
  }
))
   .then(handleResponse, (error) => Promise.reject(error))
   .then((data) => {
    return data;
   });
};

const handleResponse = (response) => {
  const data = response.data;
  if (!data?.result?.success ?? false) {
    const error = data.result;
    return Promise.reject(error);
  }

 return data;
};

function logout() {
  localStorage.removeItem("user");
  window.location.reload();
}

const getRefreshToken = () => {
  axios
    .get(ApiConstants.GET_REFRESH_TOKEN, {
      headers: {
        Authorization:
          "Bearer " + JSON.parse(localStorage.getItem("user")).refreshToken,
      },
    })
    .then((res) => {
      if (res.status === 200) {
        const user = JSON.parse(localStorage.getItem("user"));
        user.refreshToken = res.data.refreshToken;
        localStorage.setItem("user", JSON.stringify(user));
        return axios();
      }
    })
    .catch((error) => {
      console.log(error);
    });
};

Actually I tried "return new Promise" approach from Queue approach .实际上,我尝试了Queue 方法中的“return new Promise”方法

The Queue approach solved the infinite loop problem but I still encounter a 401 error with description 'staff not found' while renewing the refresh token this time.队列方法解决了无限循环问题,但我在这次更新刷新令牌时仍然遇到描述为“找不到员工”的 401 错误。 How can I solve the infinite loop problem of the async await approach?如何解决异步等待方法的无限循环问题?

Have you tried with axios.interceptors.response.eject() yet?你试过 axios.interceptors.response.eject() 了吗? It will help disable the interceptor when API called and re-enable it after.它将有助于在 API 调用时禁用拦截器并在之后重新启用它。 Example:例子:

if (error.response.status === 401 && !originalConfig._retry) {
  originalConfig._retry = true;

  **// Add axios interceptors eject to avoid loop
  axios.interceptors.response.eject();**

  let refreshToken = JSON.parse(localStorage.getItem("user"))
    .refreshToken;

  // Check for refresh token expiration

  if (jwtDecode(refreshToken).exp < new Date().getTime()) {  
    logout();                  
  }
....

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

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