How should I handle updating the JWT token in my Redux application?
Our Redux application uses JWT tokens for authentication. The access_token expires every 15 minutes and the refresh_token expires every 30 days. Both are provided by our API on every login and are stored in the local storage of the browser. If the secure endpoint receives a request with an expired token, it will return a 401 HTTP error.
Unfortunately, I don't know how to go to handle the update without negatively impacting the user. Technically speaking, here's what I would like to achieve:
- Action creator calls API with expired token
- Client receives 401 HTTP error
- The client runs a function that calls the API to get a new token (by providing a refresh token).
- If the call fails (refresh_token has expired), ask the user to re-enter their credentials to re-receive both tokens, then retry the original request.
- If the call ends, try the original request again.
I would like to have a function that will handle the update process and that will be called in the error handling part of the action creator.
Here's what I've tried so far:
export function handleError(dispatch, current_func, error, handling) {
if(error.response) {
if(error.response.status === 401 && readToken("token") !== null) {
return attemptTokenRefresh(dispatch, current_func)
}
if(error.response.status === 422 && readToken("token") === null) {
return attemptTokenRefresh(dispatch, current_func)
}
}
return(handling())
}
export function attemptTokenRefresh(dispatch, on_success) {
let token = readToken("refresh_token");
let instance = axios.create({
headers: {"Authorization": token}
});
instance.post("api/refresh").then(response => {
if (response.data["token"]) {
storeToken("token", response.data["token"]);
on_success();
}
}).catch(error => {
//TODO: Allow user to sign back (prevent wiping the state)
});
}
dispatch refers to the dispatch function provided by Redux
current_func refers to the creator of the action
the error refers to the error returned by the API
Treatmentrefers to the error handling function for other types of errors
Any help would be greatly appreciated :)
source to share
No one has answered this question yet
Check out similar questions: