简体   繁体   English

AWS放大了如何使用Redux在React应用上实现currrentSession?

[英]AWS amplify how to implement currrentSession on a React app with Redux?

AWS amplify documentation shows AWS Amplify文档显示

let session = Auth.currentSession(); // CognitoUserSession => { idToken, refreshToken, accessToken }

to retrieve Current Session which is working fine. 检索当前工作正常的会话。

However, I'm not sure how to implement this into my React app with Redux. 但是,我不确定如何通过Redux将其实现到我的React应用程序中。 All the data in store goes away when user reload the webpage along with all UIs for logged in user. 当用户重新加载网页以及已登录用户的所有UI时,存储中的所有数据都会消失。

I want to maintain logged-in stage as it is even if user refresh the page as long as CognitoUserSession is valid and maybe keep some data that I already have in the store. 我希望保持登录阶段,即使用户刷新页面也是如此,只要CognitoUserSession有效,并且也许保留一些我已经在商店中的数据即可。

What is the best way to implement this? 实现此目的的最佳方法是什么?

aws-amplify makes heavy use of localStorage . aws-amplify大量使用localStorage You can too. 你也可以

You can also use sessionStorage, which is the same thing except everything is deleted after the window closes. 您还可以使用sessionStorage,这是相同的事情,除了在关闭窗口后删除所有内容之外。

If you want save something: 如果您想保存一些东西:

window.localStorage.setItem(“itemKey”, “itemString”);

To get it back: 找回它:

const item = window.localStorage.getItem(“itemKey”);

Please note: if you want to save an object you need to JSON.stringify it and then JSON.parse it when you retrieve it. 请注意:如果要保存对象,则需要先对其进行JSON.stringify解析,然后在检索时进行JSON.parse解析。 You can only store strings. 您只能存储字符串。

I would not store sensitive information on localStorage as a general rule. 通常,我不会在localStorage上存储敏感信息。

Also, I tend to run a session check of some kind on certain components when they mount or update. 另外,我倾向于在安装或更新某些组件时对它们进行某种形式的会话检查。 For instance, you could add: 例如,您可以添加:

if (!this.props.session) { // stored session object in redux
  Auth.currentSession().then((session) => {
    handleSession({ session }); // redux action to store session
  });
}

The idea is: if the page refreshes, the components with these session checks will mount, run the if statement above, realize session is empty and, try to retrieve a new session object from Auth. 这个想法是:如果页面刷新,将安装具有这些会话检查的组件,运行上面的if语句,意识到会话为空,然后尝试从Auth检索新的会话对象。 If Auth returns an error because the user is no longer authenticated, you could add additional logic to redirect to your login screen. 如果由于用户不再经过身份验证而Auth返回错误,则可以添加其他逻辑以重定向到登录屏幕。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM