Search code examples
javascriptreactjsrecoiljs

How to control authorization flow using tokens in React.js


I made access/refresh (jwt)token verify, reissue logic in my express backend serever. Access token is saved in localstorage(client), Refresh token is saved in cookie(client), redis cache(server)

I found some ways to handle tokens in frontend

  1. using axios interceptor
  2. conditional component rendering ex) non-auth path : <*Component/> auth path : <*PrivateRoute><Component/ ></PrivateRoute>

But I'm confused about combining these. To be precise, after authorization on the path that requires authentication, at what point should the token be validated again, and how to maintain the permissions granted by the token.

When clients make a request that requires authentification, such as member information modification or payment, server need to verify it. However, if they don't make a request that requires auth, I can show them a part of the page that doesn't need to be verified. However, clients must be logged out after the token expires even without making a request.

My idea is to create a "PrivateRoute" component that encloses the entire page if it is not authenticated & "Sidebar" component that can show some parts of the page. Some parts of Sidebar is rendered only when the Access token is valid, and verify on every request(Setting axios interceptor to GET, POST "/" req) And when clients get the answer that it's a valid Access token from server, I'll save the "isLogin = true" status to the session using the Recoil. If they have no valid Access token and Refresh token, they are redirected without reissue of Access token. When "isLogin = false", only pages except Sidebar are displayed.

Here are my questions:

  1. In order to authenticate quietly without the user requesting it directly, is this the right way to validate tokens on all requests?
  2. Which method is better for me to save "isLogin" status to Recoil-persist and change the status after receiving token expiration response or to save to Recoil and reset status when page reloaded?

Solution

  • Combination of validation tokens on each requests and recoil-persist and changing the status after receiving a token expiration response will ensure that the user is logged out immediately when the token expires and it's GOOD. You will avoid unauthorized actions with your app.