在重新加载单页反应应用程序时保持 Google 登录持久
Keeping Google login persistent on reloading single page react app
我目前正在制作一个 react-redux
应用程序,它使用 Google 登录来验证用户。
该应用使用 react-google-login 实现如下:
render() {
return (
<div>
<h2> Find destinations ✈️</h2>
<GoogleLogin
clientId={this.googleClientId}
buttonText="Sign-in with Google"
onSuccess={this.responseGoogle}
/>
</div>
);
}
目前,如果我 运行 此代码,在单击登录按钮时,我能够访问登录令牌和其他用户信息,因此允许登录,但如果我重新加载页面,这会丢失,因为该应用程序恢复到原始状态。
如何保持 Google 使用 OAuth2 的登录即使在重新加载后仍然存在?
我最终使用了 localStorage
,它可以作为 window
对象使用。从 Google OAuth
中检索用户信息后,我将电子邮件、姓名等相关信息保存在 localStorage
中;这是按如下方式完成的:
在localStorage中设置键
(例如在 onLogin() 内部):
localStorage.setItem('userInfo', JSON.stringify(loginResponse));
从localStorage获取键值
(例如在 constructor() 内部):
var user = JSON.parse(localStorage.getItem('userInfo'));
清除本地存储
(例如在 onLogout() 内部):
localStorage.clear();
我目前正在制作一个 react-redux
应用程序,它使用 Google 登录来验证用户。
该应用使用 react-google-login 实现如下:
render() {
return (
<div>
<h2> Find destinations ✈️</h2>
<GoogleLogin
clientId={this.googleClientId}
buttonText="Sign-in with Google"
onSuccess={this.responseGoogle}
/>
</div>
);
}
目前,如果我 运行 此代码,在单击登录按钮时,我能够访问登录令牌和其他用户信息,因此允许登录,但如果我重新加载页面,这会丢失,因为该应用程序恢复到原始状态。
如何保持 Google 使用 OAuth2 的登录即使在重新加载后仍然存在?
我最终使用了 localStorage
,它可以作为 window
对象使用。从 Google OAuth
中检索用户信息后,我将电子邮件、姓名等相关信息保存在 localStorage
中;这是按如下方式完成的:
在localStorage中设置键 (例如在 onLogin() 内部):
localStorage.setItem('userInfo', JSON.stringify(loginResponse));
从localStorage获取键值 (例如在 constructor() 内部):
var user = JSON.parse(localStorage.getItem('userInfo'));
清除本地存储 (例如在 onLogout() 内部):
localStorage.clear();