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.
If you are using Amazon Cognito via Amplify JS and if you need to refresh tokens, then all you need to do is following: import { Auth } from 'aws-amplify'; Auth. currentSession() . then(data => console.
We'll first create an express app and then implement two routes login & refresh. The login route will get a post request, then it will check the credentials if they match it'll send a refresh token and access token in response.
To use the refresh token, make a POST request to the service's token endpoint with grant_type=refresh_token , and include the refresh token as well as the client credentials if required.
Initiate new refresh tokens (API)Pass REFRESH_TOKEN_AUTH for the AuthFlow parameter. The authorization parameter, AuthParameters , is a key-value map where the key is "REFRESH_TOKEN" and the value is the actual refresh token. Amazon Cognito returns new ID and access tokens after your API request passes all challenges.
Calling Auth.currentSession()
should solve your problem. Amplify-js abstracts the refresh logic away from you.
Under the hood currentSession()
gets the CognitoUser
object, and invokes its class method called getSession()
. It's this method, that does the following:
idToken
, accessToken
, refreshToken
, and clockDrift
from your storage.refreshSession()
method of the CognitoUser
class, which communicates to the AWS Identity Provider to generate a new set of tokens.All you have to do now is either:
Auth.currentSession()
at regular intervalsAuth.currentSession()
to get your token for each http request that you make.You could use a wrapper like this:
const getAccessJwtToken = async () => {
// Auth.currentSession() checks if token is expired and refreshes with Cognito if needed automatically
const session = await Auth.currentSession();
return session.getAccessToken().getJwtToken();
};
Lastly, this github discussion also introduces a very good manual way to refresh your token and introduces a use case for when you should explore that option.
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');
}
}
}
Updating the token method
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
}
});
})
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With