使用过期令牌发出同时 API 请求时如何避免多个令牌刷新请求

How to avoid multiple token refresh requests when making simultaneous API requests with an expired token(使用过期令牌发出同时 API 请求时如何避免多个令牌刷新请求)
本文介绍了使用过期令牌发出同时 API 请求时如何避免多个令牌刷新请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

使用 JWT 的 API 请求在 flask 和 Vue.js 中实现.JWT 存储在 cookie 中,服务器会为每个请求验证 JWT.

API request using JWT is implemented in flask and Vue.js. The JWT is stored in a cookie, and the server validates the JWT for each request.

如果令牌已过期,将返回 401 错误.如果您收到 401 错误,请按照以下代码刷新令牌,再次发出原始 API 请求.以下代码对所有请求都是通用的.

If the token has expired, a 401 error will be returned. f you receive a 401 error, refresh the token as in the code below, The original API request is made again. The following code is common to all requests.

http.interceptors.response.use((response) => {
    return response;
}, error => {
    if (error.config && error.response && error.response.status === 401 && !error.config._retry) {
        error.config._retry = true;
        http
            .post(
                "/token/refresh",
                {},
                {
                    withCredentials: true,
                    headers: {
                        "X-CSRF-TOKEN": Vue.$cookies.get("csrf_refresh_token")
                    }
                }
            )
            .then(res => {
                if (res.status == 200) {
                    const config = error.config;
                    config.headers["X-CSRF-TOKEN"] = Vue.$cookies.get("csrf_access_token");
                    return Axios.request(error.config);
                }
            })
            .catch(error => {

            });
    }
    return Promise.reject(error);
});

在令牌过期的情况下同时发出多个 API 请求时无用地刷新令牌.例如,请求 A、B 和 C 几乎同时执行.由于每个请求都返回 401,每个拦截器都会刷新令牌.

When making multiple API requests at the same time with the token expired Uselessly refreshing the token. For example, requests A, B, and C are executed almost simultaneously. Since 401 is returned with each request, Each interceptor will refresh the token.

没有真正的伤害,但我认为这不是一个好方法.有一个很好的方法可以解决这个问题.

There is no real harm, but I don't think it's a good way. There is a good way to solve this.

我的想法是首先发出 API 请求来验证令牌过期,该方法是在验证和刷新完成后发出请求A、B、C.由于 cookie 是 HttpOnly,因此无法在客户端 (JavaScript) 验证到期日期.

My idea is to first make an API request to validate the token expiration, This method is to make requests A, B, and C after verification and refresh are completed. Because cookies are HttpOnly, the expiration date cannot be verified on the client side (JavaScript).

对不起,英语不好...

Sorry in poor english...

推荐答案

你需要做的是在拦截器之外维护一些状态.说什么

What you'll need to do is maintain some state outside the interceptor. Something that says

等等,我正在获取新令牌.

Hold up, I'm in the middle of getting a new token.

最好通过保留对 Promise 的引用来实现.这样,第一个 401 拦截器可以创建 Promise,然后所有其他请求都可以等待它.

This is best done by keeping a reference to a Promise. That way, the first 401 interceptor can create the promise, then all other requests can wait for it.

let refreshTokenPromise // this holds any in-progress token refresh requests

// I just moved this logic into its own function
const getRefreshToken = () => http.post('/token/refresh', {}, {
  withCredentials: true,
  headers: { 'X-CSRF-TOKEN': Vue.$cookies.get('csrf_refresh_token') }
}).then(() => Vue.$cookies.get('csrf_access_token'))

http.interceptors.response.use(r => r, error => {
  if (error.config && error.response && error.response.status === 401) {
    if (!refreshTokenPromise) { // check for an existing in-progress request
      // if nothing is in-progress, start a new refresh token request
      refreshTokenPromise = getRefreshToken().then(token => {
        refreshTokenPromise = null // clear state
        return token // resolve with the new token
      })
    }

    return refreshTokenPromise.then(token => {
      error.config.headers['X-CSRF-TOKEN'] = token
      return http.request(error.config)
    })
  }
  return Promise.reject(error)
})

这篇关于使用过期令牌发出同时 API 请求时如何避免多个令牌刷新请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

在开发JS过程中,会经常遇到两个小数相运算的情况,但是运算结果却与预期不同,调试一下发现计算结果竟然有那么长一串尾巴。如下图所示: 产生原因: JavaScript对小数运算会先转成二进制,运算完毕再转回十进制,过程中会有丢失,不过不是所有的小数间运算会
问题描述: 在javascript中引用js代码,然后导致反斜杠丢失,发现字符串中的所有\信息丢失。比如在js中引用input type=text onkeyup=value=value.replace(/[^\d]/g,) ,结果导致正则表达式中的\丢失。 问题原因: 该字符串含有\,javascript对字符串进行了转
Rails/Javascript: How to inject rails variables into (very) simple javascript(Rails/Javascript:如何将 rails 变量注入(非常)简单的 javascript)
CoffeeScript always returns in anonymous function(CoffeeScript 总是以匿名函数返回)
Ordinals in words javascript(javascript中的序数)
getFullYear returns year before on first day of year(getFullYear 在一年的第一天返回前一年)