javascript - 跨多个浏览器窗口/选项卡刷新 JWT 一次
问题描述
我设置了一些成功刷新 JWT 令牌的代码。当用户打开多个选项卡并且它们都触发同时刷新令牌时会出现问题。每个选项卡都会获得彼此不同的新令牌,并且只有最新的令牌才能真正起作用。如何在所有浏览器选项卡上运行一次令牌刷新功能?
解决方案
我想通了。首先想一想,您应该将令牌存储在本地存储中。然后,当您请求刷新令牌时,您应该首先在本地存储中使用令牌设置 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" });
});
}
}
推荐阅读
- swift - 从 CV2 单击返回时不要重新加载 VC1 - Swift
- excel - 将 Power BI Desktop 连接到 .odc 文件
- c# - 属性总是不可变的吗?
- ios - 将当前视图控制器添加到 navigationControllerStack
- typescript - 类型注释和类型推断有什么区别?
- julia - 如何使用 Julia 0.7 将包固定到某个版本?
- c# - WPF:数据绑定 TreeViewItem -> 当先前选择另一个具有长时间运行操作的节点时,不需要选择悬停节点
- html - Firefox 中的文本对齐
- javascript - PHP exec 没有调用函数或出现死锁
- javascript - 散景单击按钮以使用 javascript 将小部件值保存到 txt 文件