Reactjs Token expiration time

一曲冷凌霜 提交于 2019-12-03 21:40:12

Do you use Redux && Redux thunk?

If so, here's the approach I followed:

  1. When the user logged in, I keep the access and refresh tokens in the Store.
  2. I'm using redux-persist to keep the tokens in the localStorage (there are other storage too), in order to persist them, when the user refreshes / reopen the app.
  3. Having a middleware, that checks if the access token is still valid before every one API request.
    1. If it's expired, try to refresh the access token, using the refresh token.
    2. If it's not expired, just execute the API request.
  4. If the user logouts or the both tokens are expired, then I clear the Store (and localStorage via redux-persist too).

More details, for the above flow, you can check in the original answer (where from I took inspirations): https://stackoverflow.com/a/36986329/4312466

If you don't use any State management libraries:

It's an option to follow the above idea, but instead of having a store, middleware, and using redux-persist, you can:

  1. Keep the tokens in localStore.
  2. Create a layer (class, function or whatever you want) in your app, that will act as middleware. Every time you want to call the API, you will call this layer firstly, that will check if the token is valid:
    1. And if so, only then will trigger the API request.
    2. If the token is expired, that layer will keep all further API requests in a queue, while trying to refresh the token.

However, if you do SPA and have complex state operations, I recommend you to use some State management library.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!