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

How do I check for token expiration and logout user?

当he/she点击注销按钮时,用户可以自行注销,但如果令牌过期he/she无法注销,因为在我的应用程序中,服务器端和前端都使用令牌.当用户点击注销按钮时,如果令牌有效,服务器和浏览器的令牌都会被清除。有可能当用户未注销且 his/her 令牌过期但未在浏览器中清除时。为了解决这种情况,我如何在每次用户访问我的应用程序时检查令牌是否过期,以便在令牌过期时从浏览器中清除令牌?

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

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

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

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

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

你可以这样做

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

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)

并且只要条件简单,您就可以在需要时随时检查令牌是否已过期。

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