首页 > 解决方案 > 跨多个浏览器窗口/选项卡刷新 JWT 一次

问题描述

我设置了一些成功刷新 JWT 令牌的代码。当用户打开多个选项卡并且它们都触发同时刷新令牌时会出现问题。每个选项卡都会获得彼此不同的新令牌,并且只有最新的令牌才能真正起作用。如何在所有浏览器选项卡上运行一次令牌刷新功能?

标签: javascriptbrowsertabs

解决方案


我想通了。首先想一想,您应该将令牌存储在本地存储中。然后,当您请求刷新令牌时,您应该首先在本地存储中使用令牌设置 Authorization 标头,然后将其请求到服务器。这是获取最新令牌所必需的。请求后,您将从服务器获得响应新令牌。将新令牌设置为本地存储并使用新令牌设置授权标头(默认)。这种方式对我有用。

  created() {
    const vm = this;
    axios.interceptors.response.use(
      function(response) {
        if (response.headers.authorization != undefined) {
          localStorage.setItem(
            "token",
            response.headers.authorization.replace("Bearer ", "")
          );
          axios.defaults.headers.common["Authorization"] =
            response.headers.authorization;
        }
        return response.data;
      },
      function(error) {
        if (error.response.status == 401) {
          vm.$store.dispatch("logout").then(() => {
            this.$router.push("/login").catch(err => {});
          });
        }
         return Promise.reject(error);
       }
    );
  },

  async mounted() {
      while (this.$store.getters.isLoggedIn) {
      await new Promise(resolve => setTimeout(resolve, 60000)).then(v => {
        axios.defaults.headers.common["Authorization"] =
          "Bearer " + localStorage.getItem("token");
        axios({ method: "get", url: "/login/refresh" });
      });
    }
 }

推荐阅读