Ser*_*ity 16 javascript jwt reactjs redux redux-saga
用户可以在他/她点击退出按钮时注销,但如果令牌过期,他/她无法注销,因为在我的应用程序中,令牌在服务器端和前端都使用.当用户单击注销按钮时,如果令牌有效,则清除服务器和浏览器中的令牌.当用户没有注销并且他/她的令牌过期但未在浏览器中清除时,有可能.为了解决这种情况,每次用户访问我的应用程序时如何检查令牌过期,如果令牌过期,请从浏览器中清除令牌?
我尝试在每次用户刷新页面或切换到另一页时在后台观看的saga.我不认为这是一种有效的方式.我认为中间件开始发挥作用.
function* loadInitialActions() {
var dateNow = new Date();
console.log(jwtDecode(token).exp < dateNow.getTime() - jwtDecode(token).iat);
const token =
JSON.parse(localStorage.getItem("user")) &&
JSON.parse(localStorage.getItem("user"))["token"];
if (
token &&
jwtDecode(token).exp < dateNow.getTime() - jwtDecode(token).iat
) {
yield put(LOGOUT_SUCCESS);
}
}
function* initialize() {
const watcher = yield fork(loadInitialActions);
yield take([INITIALIZE_ERROR, INITIALIZE_SUCCESS]);
yield cancel(watcher);
}
function* rootSaga() {
console.log("rootSaga");
yield takeLatest(INITIALIZE, initialize);
}
Run Code Online (Sandbox Code Playgroud)
所以我的问题是如果令牌从中间件到期,我如何使用令牌过期逻辑和注销用户?
Tus*_*ant 28
在我看来,中间件将是最好的选择.
你可以做这样的事情
const checkTokenExpirationMiddleware = store => next => action => {
const token =
JSON.parse(localStorage.getItem("user")) &&
JSON.parse(localStorage.getItem("user"))["token"];
if (jwtDecode(token).exp < Date.now() / 1000) {
next(action);
localStorage.clear();
}
next(action);
};
Run Code Online (Sandbox Code Playgroud)
然后你必须把它包起来 applyMiddleware
Nar*_*yan 11
const parseJwt = (token) => {
const decode = JSON.parse(atob(token.split('.')[1]));
console.log(decode);
if (decode.exp * 1000 < new Date().getTime()) {
logoutAction();
console.log('Time Expired');
}
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19681 次 |
| 最近记录: |