I'm using React on frontend and Node on backend. How I structure the authentication is, when a user logs in, a JWT token is created and stored into the user data model. That token then get stored into cookie (instead of Localstorage).
Localstorage, on the other hand, is used to store user info such as username, name, and email.
When a user logs out, the JWT token is removed, and so is the cookie and userinfo in Localstorage. I designed my React so that if there's no userinfo in Localstorage, then the private routes would become inaccessible to users. When a user logs out from all devices, all JWT tokens are removed (but cookie and Localstorage on other devices are not, since they are local).
However, this approach results in some problems:
- since removing all JWT tokens doesn't remove the userinfo from Localstorage, the private routes can still be viewed, which is undesirable
- after all JWT tokens are removed, even if a user wants to log out from another device, they can't, because now without any token, the user can't pass the authentication.
What would be a better way to structure the logOutAll component?
CodePudding user response:
In order to logout the user if there isn't any JWT available, using Axios interceptor you can catch the response error and status. So in your case the API will response with status code 401 or any other status code you're sending. If the API fails with 401 status you could add your logout logic.
Here's the code snippet using Axios interceptor, hope this helps.
axios.interceptors.response.use(
(response) => response,
(error) => {
const { status } = error.response;
if (status === 401) {
// your logout logic goes here
}
return Promise.reject(error);
}
);