如何制作候补名单和更新令牌

时间:2019-09-01 18:37:00

标签: vue.js jwt axios

每次尝试加载Web应用时,我都试图刷新JWT令牌,我需要的是:

  1. 检测是否调用了刷新令牌API。
  2. 如果令人耳目一新,请将所有其他可能的请求保存到“等待列表”中。
  3. 等待令牌刷新完成,然后更新Authorization标头并重试请求。

我已经完成了一部分工作,令牌刷新工作正常,但是我认为其他请求没有保存在等待列表中和/或授权标头未正确更新。

init.js

  const refreshTokenUrl = '/api/auth/refresh';
  let refreshingToken = false;
  let waitingList = [];

  axios.interceptors.request.use(function (config) {
    const url = config.url;

    if(url == refreshTokenUrl && refreshingToken == false) {
      refreshingToken = true;
      console.log('Trying to refresh token...'); // It's printed on console correctly
      return config;
    }

    if(refreshingToken == true) {
      // I'm not getting those logs on console even when i'm doing multiple requests at same time when it's refreshing the token.
      console.log('Push on waitingList --CONFIG:');
      console.log(config);
      return waitingList.push(config);
    }

    return config;
  });

  axios.interceptors.response.use((response) => {
    if(refreshingToken == true) {
      console.log('init.refreshingToken() --RESPONSE: ' + response.data.access_token); // It's printed on console correctly with the new token
      axios.defaults.headers.common["Authorization"] = `Bearer ${response.data.access_token}`;
      refreshingToken = false;

      waitingList.forEach(config => { return config; });
    }

    return Promise.resolve(response)

  }, (error) => {
    if(error.response.status == 401) {
      store.commit('users/logout')
      router.push({name: 'login'})
    }

    return Promise.reject(error)
  })

在控制台上打印了新的访问令牌后,其他请求给出401错误,因为这些请求是使用旧令牌完成的:

init.refreshingToken() --RESPONSE: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC8xMjcuMC4wLjE6ODAwMFwvYXBpXC9hdXRoXC9yZWZyZXNoIiwiaWF0IjoxNTY3MzYyMDY3LCJleHAiOjE1Njc5NjY4NzUsIm5iZiI6MTU2NzM2MjA3NSwianRpIjoib21UMkpYakh2QW1YV0Z5NiIsInN1YiI6MSwicHJ2IjoiODdlMGFmMWVmOWZkMTU4MTJmZGVjOTcxNTNhMTRlMGIwNDc1NDZhYSJ9.pCgk1MdD1QV-88yjSJPqNRuaawrNuw4Cvkr-sq4KlCY
Request URL: http://127.0.0.1:8000/api/orders?status=pending
Request Method: GET
Status Code: 401 Unauthorized

Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC8xMjcuMC4wLjE6ODAwMFwvYXBpXC9hdXRoXC9sb2dpbiIsImlhdCI6MTU2NzM2MjA2NywiZXhwIjoxNTY3OTY2ODY3LCJuYmYiOjE1NjczNjIwNjcsImp0aSI6IkxwRDU2eUphazBjRTJzUUUiLCJzdWIiOjEsInBydiI6Ijg3ZTBhZjFlZjlmZDE1ODEyZmRlYzk3MTUzYTE0ZTBiMDQ3NTQ2YWEifQ.bCPdnD1iQEaa0bIX00Yqqi6s7lCIHbdTfrvl0rEv_l8

希望你能帮助我。

0 个答案:

没有答案