gpt4 book ai didi

reactjs - React Router JWT 保护路由

转载 作者:行者123 更新时间:2023-12-04 14:40:40 25 4
gpt4 key购买 nike

我在 laravel 上有一个 React 应用程序,其中我有一个使用 jwt auth 的自定义登录屏幕。我在本地存储中设置了一个 token ,但如果未登录,我正在尝试保护和重定向路由。问题是在呈现路由之前检查 token 。我尝试过的一切,最终都陷入了一个巨大的循环。请帮忙。这是我的 app.jsx

require('./bootstrap');

import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux'
import Login from './components/auth/login';
import Header from './components/header/';
import store from './store';
import Dashboard from './pages/dashboard';
import jwtDecode from 'jwt-decode';
import { PropsRoute, PublicRoute, PrivateRoute } from 'react-router-with-props';


let getToken = () =>{

var auth = false;
var token = localStorage.getItem('toobiauth')

if(token){
var tokenExpiration = jwtDecode(token).exp;
var dateNow = new Date();

if(tokenExpiration < dateNow.getTime()/1000){
auth = false
}else{
auth = true
}
}else{
auth = false
}
return auth;

}


ReactDOM.render((
<Provider store={store}>
<Router>
<Header>
<Switch>
<Route exact path='/' component={Login} />
<Route exact path='/login' component={Login} />
<PrivateRoute exact path="/dashboard" authed={getToken()} redirectTo="/login" component={Dashboard}/>
</Switch>
</Header>
</Router>
</Provider>
), document.getElementById('app'))

这是我的登录
import React, { useState, useEffect } from 'react';
import { useSelector, useDispatch, connect } from "react-redux";
import Submit from '../ui/buttons/submit';
import Textfield from '../ui/inputs/textfield';
import {loginUser} from '../../actions/authactions';
import jwtDecode from 'jwt-decode';


function login(props) {

const auth = useSelector(state => state.auth)
const [username, setUsername] = useState();
const [password, setPassword] = useState();

const submitLogin = () =>{
props.dispatch(loginUser(username, password))
}

useEffect(() =>{
var token = localStorage.getItem('toobiauth')

if(token){
var tokenExpiration = jwtDecode(token).exp;
var dateNow = new Date();

if(tokenExpiration < dateNow.getTime()/1000){
console.log('expired');
}else{
props.history.push('/dashboard')
console.log('login screen')
}
}

},[auth]);


return <div className="page_wrapper">
<Textfield type="text" change={setUsername}/>
<Textfield type="password" change={setPassword}/>
<Submit action={submitLogin} width={'100%'}/>
</div>;
}

const mapStateToProps = (state) =>{
return {
app: state.app,
}
}

export default connect(mapStateToProps)(login);

最佳答案

您可以定义自己的 PrivateRoute.jsx,在该组件中,您可以检查用户是否已通过身份验证,然后允许用户路由 protected 路由,否则将用户重定向到登录路由

PrivateRoute.jsx

import React, { useEffect, useState} from 'react';
import { Route, Redirect } from 'react-router-dom'
import { useSelector } from "react-redux";

const PrivateRoute = ({ component: Component, ...rest }) => {
const auth = useSelector(state => state.auth)
const [isAuthenticated, setIsAuthenticated] = useState(null)
useEffect(() => {
let token = localStorage.getItem('toobiauth')
if(token){
let tokenExpiration = jwtDecode(token).exp;
let dateNow = new Date();

if(tokenExpiration < dateNow.getTime()/1000){
setIsAuthenticated(false)
}else{
setIsAuthenticated(true)
}
} else {
setIsAuthenticated(false)
}
// eslint-disable-next-line
}, [auth])

if(isAuthenticated === null){
return <></>
}

return (
<Route {...rest} render={props =>
!isAuthenticated ? (
<Redirect to='/login'/>
) : (
<Component {...props} />
)
}
/>
);
};

export default PrivateRoute;

App.js

import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux'
import Login from './components/auth/login';
import Header from './components/header/';
import store from './store';
import Dashboard from './pages/dashboard';
// import new PrivateRoute component defined in codeblock above
import PrivateRoute from './components/PrivateRoute'
import jwtDecode from 'jwt-decode';

ReactDOM.render((
<Provider store={store}>
<Router>
<Header>
<Switch>
<Route exact path='/' component={Login} />
<Route exact path='/login' component={Login} />
<PrivateRoute exact path='/dashboard' component={Dashboard} />
</Switch>
</Header>
</Router>
</Provider>
), document.getElementById('app'))

关于reactjs - React Router JWT 保护路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58109007/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com