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

时间:2022-11-03
本文介绍了使用过期令牌发出同时 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 请求时如何避免多个令牌刷新请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一条:JWT 未解码“JWT malformed";- 节点角度 下一条:在javascript中保护随机数?

相关文章

最新文章