如何检查令牌过期和注销用户?

时间:2017-07-08 04:11:30

标签: javascript reactjs redux jwt 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);
}

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

3 个答案:

答案 0 :(得分:24)

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

你可以做这样的事情

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

答案 1 :(得分:2)

您需要使用HOC包装Main组件。 HOC将验证令牌,如果OK则允许显示组件。如果令牌无效,则登录页面将重定向到。

const authChecker = (Component) => {
  return class extends React.Component {
    state = {
      show: false;
    }

    componentWillReceiveProps(nextProps) {
      if (nextProps.children !== this.props.children) {
        this.checkAuth();
      }
    }

    componentDidMount() {
      this.checkAuth();
    }

    checkAuth() {
      Api.checkAuth()
      .then(result => {
        if (result.success) {
          this.setState({ show: true });
        } else {
          // logout since token expired
          API.logout();
        }
      });
    }

    render() {
      return this.state.show && <Component {...this.props} />
    }
  }
}

export default authChecker(Main);

答案 2 :(得分:0)

this.serverResponse.expires_in是有效时间,以秒为单位。

var tokenexpiration: Date = new Date();
tokenexpiration.setSeconds(new Date().getSeconds() + parseInt(this.serverResponse.expires_in))
console.log(tokenexpiration);

可以将其保存到localStorage:

localStorage.setItem('expirationdate',tokenexpiration)

而且条件简单,您可以随时检查令牌是否已过期。

相关问题