How do I check for token expiration and logout user?

后端 未结 3 1109
傲寒
傲寒 2020-12-24 12:46

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 serve

3条回答
  •  南笙
    南笙 (楼主)
    2020-12-24 13:16

    You need to wrap the Main component with a HOC. The HOC will validate the token and if OK allow the component to display. If the token is invalid, the login page is redirected to.

    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 && 
        }
      }
    }
    
    export default authChecker(Main);
    

提交回复
热议问题