简体   繁体   English

JWT 中的刷新和访问令牌流

[英]Refresh and access token flow in JWT

I have developed a standard JWT system that logs in and issues an access token and a refresh token.我开发了一个标准的 JWT 系统,可以登录并发出访问令牌和刷新令牌。 The access token expires after a short amount of time and there is a route to refresh the token.访问令牌会在很短的时间后过期,并且有刷新令牌的路径。

I use axios to make requests but I am not sure how to deal with expired tokens.我使用axios发出请求,但我不确定如何处理过期的令牌。 For example, if I make a request to /secret_route with my access token and it's expired, do I need to wait for a 403 and then make a request to /refresh_token and then make the original request again?例如,如果我使用我的访问令牌向/secret_route发出请求并且它已过期,我是否需要等待403然后向/refresh_token发出请求,然后再次发出原始请求? Seems messy from a programming point of view and quite wasteful on the network.从编程的角度来看似乎很混乱,并且在网络上非常浪费。 Is there an efficient/elegant way to do this?有没有一种有效/优雅的方式来做到这一点?

I ended up with a solution that I feel is more robust than checking the timestamp.我最终得到了一个我觉得比检查时间戳更强大的解决方案。 Thanks @Bergi but I am concerned about the system clock.谢谢@Bergi,但我担心系统时钟。 I use axios interceptors to refresh the token on a 401我使用 axios 拦截器刷新 401 上的令牌

  // Request interceptor for API calls
  axios.interceptors.request.use(
    async config => {
      config.headers = { 
        'Authorization': `Bearer ${localStorage.getItem("accessToken")}`,
        'Accept': 'application/json',
      }
      return config;
    },
    error => {
      Promise.reject(error)
  });

  // Allow automatic updating of access token
  axios.interceptors.response.use(response => response, async (error) => {
    const originalRequest = error.config;
    if (error.response.status === 401 && !originalRequest._retry) {
      originalRequest._retry = true;
      const res = await axios.post('/users/token', { token: localStorage.getItem('refreshToken') });
      setToken(res.data.accessToken);

      return axios.request(originalRequest);
    }
    return Promise.reject(error);
  });

Adapted from https://thedutchlab.com/blog/using-axios-interceptors-for-refreshing-your-api-token改编自https://thedutchlab.com/blog/using-axios-interceptors-for-refreshing-your-api-token

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

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