如何在AWS Amplify-js中处理刷新令牌服务 [英] how handle refresh token service in AWS amplify-js
问题描述
在我的React项目中,我正在使用AWS Cognito用户池进行用户管理,对于用户身份验证,我正在使用AWS Cognito idToken.90分钟后,会话将终止,然后我需要使用新的idToken进行刷新.如何使用amplify-js处理AWS Cognito中的刷新令牌服务.我尝试使用 Auth.currentSession()
每1小时调用一次,但对我来说不起作用.
In my react project I am using AWS Cognito user pool for user management, for user authentication, I am using AWS Cognito idToken. after 90min the session will expire, then I need to refresh with new idToken. how to handle the refresh token service in AWS Cognito using amplify-js. I tried with Auth.currentSession()
I will call this for every 1 hour but it's not working for me.
推荐答案
经过长时间的努力,我找到了更新AWS Cognito刷新令牌的解决方案,为此,我正在使用 amazon-cognito-identity-js
After a long struggle, I found the solution to update the AWS Cognito refresh token, To do this I am using the amazon-cognito-identity-js
const AmazonCognitoIdentity = require('amazon-cognito-identity-js');
const CognitoUserPool = AmazonCognitoIdentity.CognitoUserPool;
componentWillReceiveProps(nextProps) {
let getIdToken = localStorage.getItem('idToken');
if(getIdToken !== null){
let newDateTime = new Date().getTime()/1000;
const newTime = Math.trunc(newDateTime);
const splitToken = getIdToken.split(".");
const decodeToken = atob(splitToken[1]);
const tokenObj = JSON.parse(decodeToken);
const newTimeMin = ((newTime) + (5 * 60)); //adding 5min faster from current time
//console.log(newTimeMin, tokenObj.exp)
if(newTimeMin > tokenObj.exp){
this.tokenRefresh();
console.log('token updated');
}
}
}
更新令牌方法
tokenRefresh(){
const poolData = {
UserPoolId : // Your user pool id here,
ClientId : // Your client id here
};
const userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
const cognitoUser = userPool.getCurrentUser();
cognitoUser.getSession((err, session) =>{
const refresh_token = session.getRefreshToken();
cognitoUser.refreshSession(refresh_token, (refErr, refSession) => {
if (refErr) {
throw refErr;
}
else{
//this provide new accessToken, IdToken, refreshToken
// you can add you code here once you get new accessToken, IdToken, refreshToken
}
});
})
}
这篇关于如何在AWS Amplify-js中处理刷新令牌服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!