如何检查令牌过期和注销用户? [英] How do i check for token expiration and logout user?

查看:271
本文介绍了如何检查令牌过期和注销用户?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用户可以在他/她点击退出按钮时退出,但如果令牌过期,他/她无法注销,因为在我的应用程序中,令牌在服务器端和前端都使用。当用户单击注销按钮时,如果令牌有效,则清除服务器和浏览器中的令牌。当用户没有注销并且他/她的令牌过期但未在浏览器中清除时,有可能。为了解决这种情况,每次用户访问我的应用程序时如何检查令牌过期,如果令牌过期,请从浏览器中清除令牌?

The user can logout himself when he/she clicks on the logout button but if the token is expired he/she cant logout because in my application, the token is used in both server side and front end. When user clicks on the logout button, the token from both server and browser is cleared if token is valid. There is a chance that when user does not log out and his/her token expires but is not being cleared in the browser. For addressing this situation, how do i check for token expiration every time the user visits in my app so if the token is expired, clear the token from the browser?

我在saga中尝试过每次用户刷新页面或切换到另一页时在后台观看。我不认为这是一种有效的方式。我认为中间件正在发挥作用。

I tried in saga which watches in the background every time the user refreshes in the page or switch to another page. I don't think this is an efficient way. I reckon middleware comes into play.

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

所以我的问题是如何使用令牌过期逻辑和注销用户if令牌是从中间件到期的吗?

So my question is how do i use the token expiration logic and logout user if token is expired from the middleware?

推荐答案

在我看来,中间件将是最好的选择。

In my view middleware will be the best option.

你可以这样做

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

然后你必须将它包装在 applyMiddleware

You have to then wrap it in applyMiddleware

这篇关于如何检查令牌过期和注销用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆