如何在 React.js 应用程序中刷新 JWT 令牌? [英] How to refresh JWT tokens in React.js Application?

查看:83
本文介绍了如何在 React.js 应用程序中刷新 JWT 令牌?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里检查了所有类似的问题,但没有一个是我需要的.我正在保护我的应用程序中的路由,并随每个请求发送 JWT,这里一切正常.问题是当 JWT 到期时,我需要知道如何刷新该令牌并使用户保持登录状态,而不是注销用户.

I checked all the similar questions here but none has what I need. I'm securing the routs in my App and sending the JWT with every request and everything is fine here. The issue is when the JWT expires, instead of logging out the user, I need to know how to refresh that token and keep the user logged in.

每个人都在谈论创建一个处理该问题的中间件",但没有人说如何创建该中间件以及其中包含什么?

Everyone is talking about creating a "Middleware" that handles that, but no one says how to create that middleware and what's in it?

那么,这样做的最佳实践是什么?我应该在发送任何请求之前检查 JWT 的到期日期吗?或者我应该等待401"响应然后尝试刷新令牌(我不知道该怎么做),或者究竟是什么?

So, what is the best practice in doing that? Should I check for JWT expiration date before sending any request? or should I wait for a "401" response then try to refresh the token (which I don't know how to do), or what exactly?

如果有人在 Github 上有这样的中间件或包或项目的工作示例可以帮助我解决这个问题,那就太好了.

If anyone has a working example of such a middleware or a package or a project on Github that can help me with this it would be great.

我只对流程的前端部分感兴趣,从 React 发送什么,我应该收到什么以及如何处理.

I'm only interested in the front-end part of the process, what to send from react and what should I expect to receive and what to do with it.

推荐答案

如果您正在使用 Axios(我强烈推荐),您可以在响应的 拦截器.这将适用于 Axios 发出的所有 https 请求.

If you are using Axios (which I highly recommend), you can declare your token refreshing behaviours in the response's interceptors. This will apply to all https requests made by Axios.

过程有点像

  1. 检查错误状态是否为 401
    • 如果有有效的刷新令牌:使用它来获取访问令牌
    • 如果没有有效的刷新令牌:注销用户并返回

这是一个例子:

axios.interceptors.response.use(
  (response) => {
    return response
  },
  (error) => {
    return new Promise((resolve) => {
      const originalRequest = error.config
      const refreshToken = localStorage.get('refresh_token')
      if (error.response && error.response.status === 401 && error.config && !error.config.__isRetryRequest && refreshToken) {
        originalRequest._retry = true

        const response = fetch(api.refreshToken, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            refresh: refreshToken,
          }),
        })
          .then((res) => res.json())
          .then((res) => {
            localStorage.set(res.access, 'token')

            return axios(originalRequest)
          })
        resolve(response)
      }

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

这篇关于如何在 React.js 应用程序中刷新 JWT 令牌?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆