简体   繁体   English

使用过期的 JWT 令牌注销用户

[英]Logout user on expired JWT token

I am trying to log out a user when the jwt token expires.我正在尝试在 jwt 令牌过期时注销用户。 I am trying to do it with axios interceptors, with the following code, but I get an infinite loop since it's asynchronous.我正在尝试使用 axios 拦截器,使用以下代码,但我得到一个无限循环,因为它是异步的。 Would anyone be able to tell how to go about it or if there is a better way?谁能告诉我如何 go 或是否有更好的方法? 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.在进行删除 API 调用之前清除本地存储应该会停止无限循环。 As it won't enter the if condition during the delete API call.因为它不会在 delete API 调用期间进入 if 条件。 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)而是使用状态代码 401(未经授权)

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;
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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