我正在嘗試驗證私人路線。在允許訪問之前,我通過檢查cookie來工作。但是,cookie可能會被欺騙,所以我有一個接受cookie的API端點並返回它的有效與否。使用API對私人路線進行身份驗證
工作版本,而API:
const PrivateRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={props => (
cookies.get('sessionid') ? (
<Component {...props}/>
) : (
<Redirect to={{
pathname: '/',
state: { from: props.location }
}}/>
)
)}/>
)
ReactDOM.render((
<Router>
<Switch>
<Route exact path="/" component={Login}/>
<PrivateRoute exact path="/home" component={Home} />
<PrivateRoute exact path="/upload" component={Upload}/>
<PrivateRoute exact path="/logout" component={Logout}/>
<PrivateRoute exact path="/review" component={Review}/>
<Route component={ NotFound } />
</Switch>
</Router>
), document.getElementById('root'))
附加代碼API調用:
axios.post(process.env.REACT_APP_API_URL+'/account/validate-session', {
t1_session_id: cookies.get('sessionid')
})
.then(function (response) {
if(response.data.status === "OK"){
console.log('authenticated go to private route');
} else {
console.log('not valid, redirect to index');
}
}.bind(this))
.catch(function (error) {
console.log('not valid, redirect to index');
}.bind(this));
的問題是我不知道如何將代碼API部分進入主路部分。
謝謝