gpt4 book ai didi

javascript - 使用 React Router PrivateRoute 处理 Refreshtoken

转载 作者:行者123 更新时间:2023-12-03 00:55:39 24 4
gpt4 key购买 nike

我正在使用 React-Router V4,我想移交“经过身份验证”的属性来决定是将用户发送到登录页面还是请求的页面:

PrivateRoute.js

import React from "react";
import {
Route,
Redirect,
} from "react-router-dom";
const PrivateRoute = ({ component: Component, authenticated, ...rest }) => (
<Route
{...rest}
render={props =>
authenticated ? (
<Component {...props} />
) : (
<Redirect
to={{
pathname: "/login",
state: { from: props.location }
}}
/>
)
}
/>
)
export default PrivateRoute;

我的 App.js 看起来像这样:

class App extends Component {

is_authenticated() {
const token = localStorage.getItem('access_token');
//if token is not expired send on the way
if (token && jwt_decode(token).exp > Date.now() / 1000) {
return true;
} else {
// if token is expired try to refresh
const refresh_token = localStorage.getItem('refresh_token');
if(refresh_token) {
axios.post(config.refresh_url,{},{
headers: {"Authorization": `Bearer ${refresh_token}`},
"crossdomain": true,
mode: 'no-cors',}).then(
response => {
const access_token = response.data.access_token;
localStorage.setItem('access_token', access_token)
return access_token ? true : false
}
)
}
}
return false
}

render() {
const client = this.client;
return (
<Router>
<div>
<Route exact path="/login" component={Login} />
<PrivateRoute exact path="/" component={Home} authenticated={this.is_authenticated()} />
</div>
</Router>
);
}
}

export default App;

由于 Axios 调用是异步的,因此组件会在调用完成之前渲染。

如何让渲染等待 token 刷新?

最佳答案

我会将 isAuthenticated 保留在应用程序组件状态中。然后,您可以在 isAuthenticated 调用中使用 setState 来重新渲染结果。当 token 过期时,这一点也很重要。

关于javascript - 使用 React Router PrivateRoute 处理 Refreshtoken,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52854639/

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