How can I check the token expiration date and log out?

The user can log out on their own when he presses the logout button, but if the token has expired he / she cannot log out because in my application the token is used both on the server side and on the front side. When the user clicks the exit button, the token from the server and browser is cleared if the token is valid. There is a possibility that when the user is not logged out and his token does not expire, it is not cleared in the browser. To solve this situation, how can I check the token expiration every time the user visits my application, so if the token has expired, clear the token from the browser?

I've tried in a saga that looks in the background every time the user refreshes on a page or switches to another page. I don't think this is an efficient way. I believe 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);
}

      

So my question is how to use the token expiration logic and log out if the token expired from the middleware?

+3


source to share


2 answers


In my opinion, middleware would be the best option.

You can do something like this



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

      

Then you have to wrap it in applyMiddleware

+12


source


You need to wrap the main HOC component. The HOC will validate the token, and if OK will enable the display of the component. If the token is invalid, the login page is redirected.



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

      

+1


source







All Articles