reactjs - React Redux Auth 中间件
问题描述
我正在使用 react/redux 做一个登录应用程序,这是我的流程。
- 用户使用电子邮件/密码对登录并收到我存储在 cookie 中的令牌。
- 获得令牌后,我可以通过在
/auth
检索他的个人详细信息(名字、姓氏、电子邮件)的端点上发出请求来获取他的凭据。
我有一个 PrivateRoute 用于进行身份验证检查,但是我想触发对所有路由的身份验证检查,而不仅仅是私有路由。这样,如果用户正在查看主页,我仍然可以在导航中显示他的名字(例如) 主要问题似乎是调用 auth 操作的正确位置。
应用程序.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的一部分,其中定义了身份验证操作
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
});
}
}
我的一个想法是创建一个父 Route 类来进行路由,并在auth
那里调用。
解决方案
为了克服它,我使用 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。一旦触发登录或注销过程,就会切换身份验证并相应地呈现页面。我还保留了身份验证过程的状态,以便在身份验证检查期间不会向用户显示私人数据。
推荐阅读
- php - 如何将运费与产品实际价格相加?新的
- typescript - 打字稿:将标记的联合转换为联合类型
- azure - 在 ARM 中,如何在数组集合中包含可选的参数化对象?
- c++ - 使用 MSVC 调试类型
- sas - 使用不同类型的变量附加 sas 表(字符在基础上,数字在数据上)
- c# - ASP.NET Web Application Core - 如何根据角色将 AspNetUsers 中的数据操作到不同的表?
- python - 无法在 python 中使用 lxml 从 XML 正确获取预期项目
- rhel8 - 重新启动:加载共享库时出错:libip4tc.so.2:无法打开共享对象文件:没有这样的文件或目录
- python-3.x - 如何将输出放在一行中?
- android - 从库模块中删除未使用的类