简体   繁体   中英

Live Conditional Render , Automatic User logout after Jwt expires

When the expiration date is less than the current time or date, I want it to automatic logout. However, it appears that after I input the expiry date, I must refresh before it logs out, and the worst case scenario is that it has been more than an hour, which is my typical inputted expiry date, and when I try to add some input, like maybe add posts it alerts me that user must be logged in which I know put that alert if the user isn't logged in anymore if the token is expired. Is there any way to solve the problem or issue I'm having right now? I know there is, but my lack of expertise isn't helping me come up with any more solutions.

Code


const initialState = {
  user: null,
};

if (typeof window !== "undefined") {
  if (localStorage.getItem("jwtToken")) {
    const decodedToken = jwtDecode(localStorage.getItem("jwtToken"));

    if (decodedToken.exp * 1000 < Date.now()) {
      localStorage.removeItem("jwtToken");
      window.location.href = "/login";
    } else {
      initialState.user = decodedToken;
    }
  }
}

And in my backend, I simply put in 5000 milliseconds or 5 seconds to see if my application was running, and the jwt token is saved in localStorage whenever I login. This code works, but you'll need to reload the page before the logout method takes effect.

Thank you for your assistance, and please leave any questions in the comments section below.

I found a way, but I don't think this is a good practice this is the code that I did:

Code

  function login(userData) {
    localStorage.setItem("jwtToken", userData.token);

    const decodedToken = jwtDecode(userData.token);

    dispatch({
      type: "LOGIN",
      payload: userData,
    });

    setTimeout(() => {
      localStorage.removeItem("initialTime");
      logout();
      router.push("/login");
      toast.error("Session expired", shortToastConfig);
    }, decodedToken.exp * 1000 - Date.now());
  }

It will auto logout because the expiry date is 1 hour after I login, and you are welcome to adjust my code if it is not as efficient or best practice. Another issue is that when I refresh the page in the between before the token expires, it does not auto logout, implying that the settimeout capability is doesn't work maybe after the refresh has been made?

Thanks for your help, and please leave a comment if you need more code to try this out.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM