[英]Reactjs Redirect to protected page after login not working after Authenticated
[英]How to create a protected route after login in reactjs
我对反应很陌生。 我正在尝试创建一个项目,用户必须在其中登录才能访问页面,并且我想保护一条只有在成功登录后才能访问的路由。 我不想要花哨的用户管理或类似的东西,所以请不要推荐上下文或 redux。 我只希望我的 localhost:3000/editor 只有在登录后才能访问,如果有人试图在没有登录的情况下访问 /editor 那么他们将被重定向到登录页面。 所以像 isAuthenicated: true/false 这样的东西在我的情况下会很好我相信但我不确定如何在我的 webapp 中传递它。 如果有人可以告诉我如何做到这一点,我会非常高兴? 我创建了这个,但有很多错误
应用程序.js
import React, {useState} from "react";
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";
import "./App.css";
import Login from "./login";
import Dashboard from "./dashboard";
function App() {
const [loggedIN, setLoggedIN]=useState(false);
let privateRoutes = null;
if(loggedIN){
privateRoutes =(
<Route path="/dashboard" component={Dashboard} />
)}
return (
<>
<Router>
<div className="container">
<nav className="navbar navbar-expand-lg navheader">
<div className="collapse navbar-collapse">
<ul className="navbar-nav mr-auto">
<li className="nav-item">
<Link to={"/Login"} className="nav-link">
Login
</Link>
</li>
</ul>
</div>
</nav>
<br />
<Switch>
<Route exact path="/login" component={Login} />
{privateRoutes}
</Switch>
</div>
</Router>
</>);
}
export default App;
登录.js
import React, { Component } from "react";
import MuiThemeProvider from "material-ui/styles/MuiThemeProvider";
import AppBar from "material-ui/AppBar";
import RaisedButton from "material-ui/RaisedButton";
import TextField from "material-ui/TextField";
import { Link } from "react-router-dom";
import "./loginForm.css";
class Login extends Component {
constructor(props) {
super(props);
this.state = {
email: "",
password: ""
};
this.onchange = this.onchange.bind(this);
}
onchange(e) {
this.setState({ [e.target.name]: e.target.value });
}
performLogin = async () => {
var body = {
password: this.state.password,
email: this.state.email
};
const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json"
},
body: JSON.stringify(body)
};
const url = "/api/authenticate";
try {
const response = await fetch(url, options);
const text = await response.text();
if (text === "redirect") {
this.props.setState({loggedIN: true})
this.props.history.push(`/dashboard`);
} else {
console.log("login failed");
window.alert("login failed");
}
} catch (error) {
console.error(error);
}
};
render() {
return (
<>
<div className="loginForm">
<MuiThemeProvider>
<TextField
hintText="Enter your Email"
floatingLabelText="Email"
onChange={(event, newValue) => this.setState({ email: newValue })}
/>
<br />
<TextField
type="password"
hintText="Enter your password"
floatingLabelText="password"
onChange={(event, newValue) =>
this.setState({ password: newValue })
}
/>
<br />
<RaisedButton
label="Submit"
primary={true}
style={style}
onClick={event => this.performLogin(event)}
/>
</MuiThemeProvider>
</div>
</>
);
}
}
const style = {
margin: 15
};
export default Login;
编辑页面
import React, { Component } from "react";
class Dashboard extends Component {
constructor(props) {
super(props);
}
logout=()=>{
this.setState({loggedIN: false)}
}
render() {
return (
<div>hello</div>;
<button onCLick={logout}>Logout</button>
)
}
}
export default Dashboard;
编辑:代码沙盒
成功登录后,您可能会获得用于授权的令牌。 因此,成功登录后,您可以将身份验证令牌存储在 cookie 中。
install - npm i universal-cookie --save
登录.js
import MuiThemeProvider from "material-ui/styles/MuiThemeProvider";
import AppBar from "material-ui/AppBar";
import RaisedButton from "material-ui/RaisedButton";
import TextField from "material-ui/TextField";
import { Link } from "react-router-dom";
import "./loginForm.css";
import Cookies from 'universal-cookie';
const cookies = new Cookies();
class Login extends Component {
constructor(props) {
super(props);
this.state = {
email: "",
password: ""
};
this.onchange = this.onchange.bind(this);
}
onchange(e) {
this.setState({ [e.target.name]: e.target.value });
}
performLogin = async () => {
var body = {
password: this.state.password,
email: this.state.email
};
const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json"
},
body: JSON.stringify(body)
};
const url = "/api/authenticate";
try {
const response = await fetch(url, options);
const text = await response.text();
// here you will get auth token in response
// set token in cookie like cookie.set('token', response.token);
cookies.set('loggedin', true);
if (text === "redirect") {
this.props.setState({loggedIN: true})
this.props.history.push(`/dashboard`);
} else {
console.log("login failed");
window.alert("login failed");
}
} catch (error) {
console.error(error);
}
};
render() {
return (
<>
<div className="loginForm">
<MuiThemeProvider>
<TextField
hintText="Enter your Email"
floatingLabelText="Email"
onChange={(event, newValue) => this.setState({ email: newValue })}
/>
<br />
<TextField
type="password"
hintText="Enter your password"
floatingLabelText="password"
onChange={(event, newValue) =>
this.setState({ password: newValue })
}
/>
<br />
<RaisedButton
label="Submit"
primary={true}
style={style}
onClick={event => this.performLogin(event)}
/>
</MuiThemeProvider>
</div>
</>
);
}
}
const style = {
margin: 15
};
export default Login;
之后,在仪表板组件中检查 cookie 中的登录布尔值(如果它存在),则它已登录并通过身份验证。 例如。
仪表板.js
import React, { Component } from "react";
import {Redirect} from 'react-router-dom'
import Cookies from 'universal-cookie';
const cookies = new Cookies();
class Dashboard extends Component {
constructor(props) {
super(props);
}
logout=()=>{
this.setState({loggedIN: false)}
cookies.set('loggedin', false);
}
render() {
// notice here
if (!cookies.get('loggedin')) {
return (<Redirect to={'/login'}/>)
}
return (
<div>hello</div>;
<button onCLick={logout}>Logout</button>
)
}
}
export default Dashboard;
我认为你这里有错误或者最好改变它
let privateRoutes = null;
if(loggedIN){
privateRoutes =(
<Route path="/dashboard" component={Dashboard} />
)}
将其更改为
let privateRoutes =()=>{
if(loggedIN){
return(
<Route path="/dashboard" component={Dashboard} />
)
}
}
但你不需要这个! 你可以使用渲染路线
<Route path="/home" render={() => {
if(loggedIN){
return(<Dashboard ...props/>)
}else{
return(<Login ...props/>)
}
}} />
请注意,在 App.js 中登录后 ((loggedIN)) 将为 true 并且它会自动转到仪表板
参考: https : //reacttraining.com/react-router/web/api/Route/render-func
在这里你有大错误:
import React, { Component } from "react";
class Dashboard extends Component {
constructor(props) {
super(props);
}
// logout function should not be here it should write in app.js and pass to
// this component with props and just call here if needed
// and you should use this.logout = () ...
logout=()=>{
// and here
this.setState({loggedIN: false**)**}
}
render() {
// here!!! jsx element should wrapped with an element
return (
// <div>
<div>hello</div>;
<button onCLick={logout}>Logout</button>
//</div>
)
}
}
export default Dashboard;
最有效的方法是使用 [redux-auth-wrapper][2] 之类的 HOC 拆分路由和管理重定向
应用程序.js
import { createDevTools } from 'redux-devtools'
import LogMonitor from 'redux-devtools-log-monitor'
import DockMonitor from 'redux-devtools-dock-monitor'
import React from 'react'
import ReactDOM from 'react-dom'
import { createStore, combineReducers, applyMiddleware, compose } from 'redux'
import { Provider } from 'react-redux'
import thunkMiddleware from 'redux-thunk'
import * as reducers from './reducers'
import App from './components/App'
const reducer = combineReducers(Object.assign({}, reducers, {}))
const DevTools = createDevTools(
<DockMonitor toggleVisibilityKey="ctrl-h"
changePositionKey="ctrl-q">
<LogMonitor theme="tomorrow" />
</DockMonitor>
)
const enhancer = compose(
// Middleware you want to use in development:
applyMiddleware(thunkMiddleware),
DevTools.instrument()
)
// Note: passing enhancer as the last argument requires redux@>=3.1.0
const store = createStore(reducer, enhancer)
ReactDOM.render(
<Provider store={store}>
<div>
<App />
{/* <DevTools /> */}
</div>
</Provider>,
document.getElementById('mount')
)
认证.js
import locationHelperBuilder from 'redux-auth-wrapper/history4/locationHelper'
import { connectedRouterRedirect } from 'redux-auth-wrapper/history4/redirect'
import connectedAuthWrapper from 'redux-auth-wrapper/connectedAuthWrapper'
import Loading from './components/Loading'
const locationHelper = locationHelperBuilder({})
const userIsAuthenticatedDefaults = {
authenticatedSelector: state => state.user.data !== null,
authenticatingSelector: state => state.user.isLoading,
wrapperDisplayName: 'UserIsAuthenticated'
}
export const userIsAuthenticated = connectedAuthWrapper(userIsAuthenticatedDefaults)
export const userIsAuthenticatedRedir = connectedRouterRedirect({
...userIsAuthenticatedDefaults,
AuthenticatingComponent: Loading,
redirectPath: '/login'
})
export const userIsAdminRedir = connectedRouterRedirect({
redirectPath: '/',
allowRedirectBack: false,
authenticatedSelector: state => state.user.data !== null && state.user.data.isAdmin,
predicate: user => user.isAdmin,
wrapperDisplayName: 'UserIsAdmin'
})
const userIsNotAuthenticatedDefaults = {
// Want to redirect the user when they are done loading and authenticated
authenticatedSelector: state => state.user.data === null && state.user.isLoading === false,
wrapperDisplayName: 'UserIsNotAuthenticated'
}
export const userIsNotAuthenticated = connectedAuthWrapper(userIsNotAuthenticatedDefaults)
export const userIsNotAuthenticatedRedir = connectedRouterRedirect({
...userIsNotAuthenticatedDefaults,
redirectPath: (state, ownProps) => locationHelper.getRedirectQueryParam(ownProps) || '/protected',
allowRedirectBack: false
})
基于React Router v4 的工作示例
我所做的
在主路由中(通常是 App.js):
import { userIsAuthenticated, userIsNotAuthenticated } from './auth';
// ...code
const isNotAuth = userIsNotAuthenticated(Login);
const isAuth = userIsAuthenticated(AuthRoutes);
// ...code
<Switch>
<Route exact path="/login" component={isNotAuth} /> // Notice the *exact* path
<Route path="/" component={isAuth} /> // Notice the *not exact path*
<Route path="" component={NotFoundPage} />
</Switch>
AuthRoutes.js
只有在用户通过身份验证时才会提供这些路由
// ...code
<Switch>
<Route exact path="/homepage" component={HomePage} />
// ...other routes
</Switch>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.