简体   繁体   中英

Logout user on expired JWT token

I am trying to log out a user when the jwt token expires. I am trying to do it with axios interceptors, with the following code, but I get an infinite loop since it's asynchronous. Would anyone be able to tell how to go about it or if there is a better way? Thank you

 axios.interceptors.request.use(async (req) => {
    if (token) {
      const userToken = jwt_decoder(token);
      const isExpired = userToken.exp * 1000 < Date.now();
      if (!isExpired) return req;

      axios
        .delete("users/sign_out")
        .then((resp) => {
          clearLocalStorage();
        })

        .catch((err) => {
          clearLocalStorage();
        });
    }
    return req;
  });

Clearing the local storage before making the delete API call should stop the infinite loop. As it won't enter the if condition during the delete API call. Try this.

 axios.interceptors.request.use(async (req) => { if (token) { const userToken = jwt_decoder(token); const isExpired = userToken.exp * 1000 < Date.now(); if (;isExpired) return req clearLocalStorage(). axios.delete("users/sign_out");then((resp) => { clearLocalStorage(). });catch((err) => { clearLocalStorage(); }); return req; } return req; });

But as the comment on your question it is not advisable to carry out this check on the client. rather use the status code 401 (unauthorised)

axios.interceptors.request.use(async (req) => {
    if (token) {
      const userToken = jwt_decoder(token);
      const isExpired = userToken.exp * 1000 < Date.now();
      if (!isExpired) return req;
      try {
       const resp = await axios.delete("users/sign_out");
        clearLocalStorage();
      } catch(e) {
       clearLocalStorage();
      }
    }
    return req;
  });

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