我正在尝试在React应用程序中实现简单的身份验证系统。到目前为止,我已经与Google实现了OAuth。在用户成功登录后,我从Google获得此令牌,然后将其存储在Cookie中。该部分正常工作。.因此,在App.jsx组件中,我声明了路由并创建了PriveRoute组件。我只添加必要的代码
在App.jsx中路由
<Switch>
<Route path={`${this.props.match.url}/checkout`} component={Checkout} />
<PrivateRoute path={`${this.props.match.url}/dashboard`} authenticated={Cookies.get('authToken')} component={Dashboard} />
<Route path={`${this.props.match.url}/profile`} component=
</Switch>
PrivateRoute
const PrivateRoute = ({ authenticated, component: Component, ...rest }) => {
{ console.log(authenticated) }
return <Route {...rest} render={(props) => (
authenticated
? <Component {...props} />
: this.props.history.push('/login')
)} />
}
这两个主题都位于App.jsx的render方法中
我使用js-cookie
来使用Cookies。
因此,在用户成功登录后,我已经通过快递服务器将authToken
设置为cookie。因此,之后,快速服务器将重定向到app/dashboard
url。所以在App.jsx中,因为我有路线。用户首次使用Google登录后,它会重定向到仪表板,并且可以正常工作。
但是,如果我刷新页面,它将始终重定向到登录页面。
我不知道发生了什么。任何帮助将不胜感激!
答案 0 :(得分:0)
尝试使用Redirect
组件,而不要推送
import { Redirect } from "react-router-dom"
您必须立即渲染一个组件
const PrivateRoute = ({ authenticated, component: Component, ...rest }) => {
{ console.log(authenticated) }
return <Route {...rest} render={(props) => (
authenticated
? <Component {...props} />
: <Redirect to={{pathname: "/login", state: { from: props.location }}}/>
)} />
}
答案 1 :(得分:0)
检查刷新后是否维护了authToken。如果Cookie在刷新后仍然存在,而只是会话令牌,则客户端会认为用户已注销。
这可能有帮助:
Keeping user logged in after refresh/using refresh token with Google OAuth2 in React app