首页 文章

React Redux Auth Middlware

提问于
浏览
0

我正在使用react / redux进行登录应用程序,这是我的流程 .

  • 用户使用电子邮件/密码对登录并接收令牌,我将其存储在cookie中 .

  • 一旦我有了令牌,我就可以通过在 /auth endpoints 上执行请求来获取他的凭据,该 endpoints 检索他的个人详细信息 - 名字,姓氏,电子邮件 .

我有一个用于进行身份验证的PrivateRoute,但是我想触发所有路由的auth检查,而不仅仅是私有路由 . 这样,如果用户正在查看主页,我仍然可以在导航中显示他的名字(例如)主要问题似乎是调用auth操作的正确位置 .

App.js

import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import { Provider } from 'react-redux';
import store from './store';

// Styling
import './App.css';

// Privat route
import PrivateRoute from './routes/PrivateRoute';

// Common
import Navigation from './components/common/Navigation';

// Components
import Login from './components/Login';
import Home from './components/Home';
import Profile from './components/Profile';
import ArticlesList from './components/Profile/ArticlesList';
import ArticleForm from './components/Profile/ArticleForm';

const App = () => (
    <Provider store={store}>
        <Router>
            <Switch>
                {/* Public routes */}
                <Route exact path="/" component={Home} />
                <Route exact path="/login" component={Login} />

                {/* Private routes */}
                <PrivateRoute exact path="/profile" component={Profile} />
                <PrivateRoute exact path="/profile/articles" component={ArticlesList} />
                <PrivateRoute exact path="/profile/articles/new" component={ArticleForm} />
                <PrivateRoute exact path="/profile/articles/:id(\d+)" component={ArticleForm} />
            </Switch>
        </Router>
    </Provider> 
);

export default App;

这是我的 userActions.js 的一部分,其中定义了auth动作

export const auth = () => async dispatch => {
    dispatch({ type: AUTH_USER_REQUEST });

    try{
        let data = await UserService.auth();

        dispatch({
            type: AUTH_USER_SUCCESS,
            payload: data
        });
    }catch(err){
        dispatch({
            type: AUTH_USER_ERROR,
            payload: err.message
        });
    }
}

我的一个想法是创建一个父路由类来进行路由,并在那里调用 auth .

1 回答

  • 0

    为了克服它,我使用Redux做了类似下面的事情:

    <Switch>
      <Route 
        path="/"
        component={this.props.auth.authenticationInProgress ? BlankPage : 
          (this.props.auth.isAuthenticated ? SegmentPage : LoginPage)}
        exact={true}
      />
      <Route component={NotFoundPage}/>
    </Switch>
    

    如果用户登录,则Route会呈现SegmentPage . 否则它呈现LoginPage . 触发登录或注销过程后,将切换身份验证并相应地呈现页面 . 此外,我保持身份验证过程的状态,以便在身份验证检查期间不向用户显示私有数据 .

相关问题