使用Cookie进行客户端身份验证和受保护的路由

时间:2019-02-16 17:08:45

标签: reactjs cookies redux jwt react-router-v4

我目前正在使用无状态JWT令牌在我的应用中进行身份验证。在客户端,我正在运行一个具有受保护路由的React + Redux应用程序。它使用HOC来实现,该HOC会检查jwt令牌是否存在并允许基于该令牌的路由。

我最近读到,本地存储不是存储JWT令牌的好地方。因此,我切换到在cookie中使用jwt。

但是问题是使用cookie时如何在客户端实现受保护的路由。 我在react应用中使用react-router-dom进行路由。

1 个答案:

答案 0 :(得分:0)

简单,只需使用if if

App.js
import { connect } from "react-redux";
import { Redirect, Route, Switch } from "react-router";
import "./App.css";
import Auth from "./Components/Pages/Auth/Auth";
import Logout from "./Components/Pages/Auth/Logout/Logout";
import { checkAuthStatus } from "./Components/store/actions";

function App(props) {
  useEffect(() => {
    props.checkAuthStatus(); // checking authentication status of user on each reload
  }, []);

  // filtering routes based on the authentication state of user
  const getRoutes = () => {
    if (props.auth) {
      return <Switch>{/* ...authenticated routes */}</Switch>;
    } else {
      // unauthenticated routes
      return (
        <Switch>
          <Route path="/auth" component={Auth} />
          <Route path="/logout" component={Logout} />
          <Redirect to="/auth" />
        </Switch>
      );
    }
  };
  console.log(props.error);
  return (
    <div className="App">
      {
        <Suspense fallback={<div>loading...</div>}>
          {props.loading ? <div>Authenticating...</div> : getRoutes()}
        </Suspense>
      }
    </div>
  );
}

const mapStateToProps = (state) => {
  return {
    auth:
      state.login.data.token !== undefined && state.login.data.token !== null,
    loading: state.login.loading,
    error: state.login.error,
  };
};

const mapDispatchToProps = (dispatch) => {
  return {
    checkAuthStatus: () => dispatch(checkAuthStatus()),
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(App);

actions.js

import { axiosInstance } from "../../Utility/axiosInstance";
import { getCookie } from "../../Utility/cookies";
import * as actionTypes from "./actionTypes";

export const loginStart = () => {
  return {
    type: actionTypes.LOGIN_START,
  };
};
export const loginFailure = (error) => {
  return {
    type: actionTypes.LOGIN_FAILURE,
    error,
  };
};
export const loginSuccess = (data) => {
  return {
    type: actionTypes.LOGIN_SUCCESS,
    data,
  };
};

export const checkAuthStatus = () => {
  return (dispatch) => {
    dispatch(loginStart());
    let token = getCookie("token");
    axiosInstance
      .post("/checkauthstatus", { id: token })
      .then((res) => {
        console.log(res.data);
        dispatch(loginSuccess(res.data));
      })
      .catch((err) => {
        console.log(err);
        let error = "something went wrong";
        if (err.response) {
          error = err.response.message;
        }
        dispatch(loginFailure(error));
      });
  };
};