Reactjs Token expiration time

2019-04-16 03:15发布

问题:

i making single page web with login with Reactjs. Problem is how and where to save token expire time. Do i need to save in sessionStore, but when browser closes all data will be deleted. Local Store? But then data will be forever. Or i can save in localStore and in every event i have to add function, that checks expire time from localStore, when event triggered successfully update localstore again? but code will look horrible... and how about performance issues? Is this approuche acceptible?

回答1:

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.