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?
Do you use Redux && Redux thunk?
If so, here's the approach I followed:
- When the user logged in, I keep the access and refresh tokens in the Store.
- 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.
- Having a middleware, that checks if the access token is still valid before every one API request.
- If it's expired, try to refresh the access token, using the refresh token.
- If it's not expired, just execute the API request.
- 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:
- Keep the tokens in
localStore
. - 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:
- And if so, only then will trigger the API request.
- 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.
来源:https://stackoverflow.com/questions/50562104/reactjs-token-expiration-time