Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to refresh JWT tokens in React.js Application?

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?

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?

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.

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.

like image 737
Ruby Avatar asked Feb 05 '19 09:02

Ruby


People also ask

How refresh JWT Token react JS?

React Refresh Token with JWT overview – A legal JWT must be added to HTTP Header if Client accesses protected resources. – With the help of Axios Interceptors, React App can check if the accessToken (JWT) is expired (401), sends /refreshToken request to receive new accessToken and use it for new resource request.

Can we refresh JWT Token?

JWT (JSON Web Token) It may also have a validity period. Once this validity period has elapsed, the server will no longer allow access to resources with this token. In this step, the user will have to get a new access token by reauthentication or with some additional method: refresh token.


1 Answers

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.

The process is something like

  1. Checking if the error status is 401
    • If there is a valid refresh token: use it to get the access token
    • if there is no valid refresh token: log the user out and return
  2. Redo the request again with the new token.

Here is an example:

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)
    })
  },
)
like image 104
lehoang Avatar answered Sep 29 '22 15:09

lehoang