当jwt过期时(我的默认值为30分钟),我需要被警告,有人可以帮助我吗?我希望警告用户并将其重定向到登录页面
const isInRole = (role: string): boolean => {
try {
const jwt = localStorage.getItem("token");
if (jwt) {
var user = jwtDecode<User>(jwt);
if (typeof user.roles === "string") return user.roles.toLowerCase() === role.toLowerCase();
return user.roles.some(r => r == role);
}
return false;
} catch (ex) {
}
return false;
};
//here´s where I check the jwt value
const isAuthenticated = () => {
try {
const jwt = localStorage.getItem("token");
if (jwt) {
jwtDecode<User>(jwt);
return true;
}
} catch (ex) {}
return false;
};
const getJWT = () => localStorage.getItem("token");
http.setJWT(getJWT());
你能告诉我我想念什么吗?
答案 0 :(得分:0)
在从本地存储中加载令牌时,但在将令牌设置为应用程序状态之前,请检查令牌是否已过期:
let token = localStorage.getItem("token")
let payload = jwtDecode(token)
// payload.exp should contain the expiration epoch set upon creation
if (payload.exp > Math.round(Date.now() / 1000)) {
alert("Your token has expired!")
}
如果您没有到期字段,但是有一个“ issued-at”(iat
)字段,则以下逻辑也将足以检查自发出之日起已经过30分钟:
const TIME_DELTA = 30 * 60 * 1000; // convert 30 minutes to epoch time
if (payload.iat + TIME_DELTA <= Math.round(Date.now() / 1000)) {
alert("Your token was issued more than 30 minutes ago!")
}