React中的身份验证和重定向

时间:2018-08-18 15:56:56

标签: reactjs authentication react-router

我目前在一个React项目中,我有一个使用令牌处理身份验证的后端,还有一个可以通过对服务器的异步调用对用户进行身份验证的React前端。

这就是我所拥有的:

  • 主页
  • 登录页面
  • 注册页面

这是我要实现的目标:

  • 当用户沿任何路线行驶且未通过身份验证时->重定向到登录页面
  • 用户登录时->重定向到首页

我当前的代码:

App.js

class App extends Component {
  render() {
    return (
      <Router>
        <div>
          <ul>
            <li>
              <Link to="/register">Register</Link>
            </li>
            <li>
              <Link to="/login">Login</Link>
            </li>
            <li>
              <Link to="/TodoList">Protected Page</Link>
            </li>
          </ul>
          <Route path="/register" component={Register} />
          <Route path="/login" component={Login} />
          <PrivateRoute path="/TodoList" component={TodoList} />
        </div>
      </Router>
    );
  }
}

PrivateRoute.js

import { verifAuth } from "./verifAuth";

class PrivateRoute extends Component {
  state = {
    loading: true,
    isAuthenticated: false
  };

  componentDidMount() {
    verifAuth().then(isAuthenticated => {
      this.setState({
        loading: false,
        isAuthenticated
      });
    });
  }

  render() {
    const { component: Component, ...rest } = this.props;
    if (this.state.loading) {
      return <div>LOADING</div>;
    } else {
      return (
        <Route
          {...rest}
          render={props => (
            <div>
              {!this.state.isAuthenticated && (
                <Redirect
                  to={{
                    pathname: "/login",
                    state: { from: this.props.location }
                  }}
                />
              )}
              <Component {...this.props} />
            </div>
          )}
        />
      );
    }
  }
}

verifAuth.js

export async function verifAuth() {
  return await axios
    .post("/auth", {
      token: localStorage.getItem("token")
    })
    .then(res => {
      if (res.status === 200) return true;
      return false;
    })
    .catch(err => console.log(err));
}

login.js中的重定向方法

const { from } = this.props.location.state || { from: { pathname: "/" } };
if (this.state.redirect) {
  return <Redirect to={from} />;
}

1 个答案:

答案 0 :(得分:0)

为此,我将使用React Router DOM,请遵循此文档https://reacttraining.com/react-router/web/example/auth-workflow,您将获得它!

相关问题