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.
4 Answers
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:
- Get
idToken
,accessToken
,refreshToken
, andclockDrift
from your storage. - Validate the tokens (i.e. idToken, and accessToken) to see if they have expired or not.
- If tokens are valid, return current session.
- If tokens are expired, invoke the
refreshSession()
method of theCognitoUser
class, which communicates to the AWS Identity Provider to generate a new set of tokens.
All you have to do now is either:
- Make sure to call
Auth.currentSession()
at regular intervals - Always call
Auth.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.
-
2I think it should be getIdToken() as getAccessToken() didn't work for us. – user.io Mar 04 '21 at 12:14
-
@user.io But wouldn't getIdToken() give the idToken? we want the accessToken to be replaced into the api request headers right? Then we use idToken? – Shiraaz May 27 '22 at 11:38
Amplify will automatically keep the session fresh so long as it's active (i.e. the user is making api calls, etc.).
If you want to force the session to stay active, even though they are not actively using your API, then the easiest thing to do would be to call Auth.currentAuthenticatedUser()
at regular intervals.

- 7,926
- 1
- 27
- 33
-
thank you for your replay, for auto-update I need to enable any options in my user pool settings? and I tried to do this using `amazon-cognito-identity-js` but that also not working for me – Nov 20 '18 at 13:48
-
1No- Amplify automatically tries to refresh if the access token has timed out (which happens after an hour). Note that you configure the _refresh token expiration_ in the Cognito User Pools console (General settings > App clients > Refresh token expiration (days))- this is the maximum amount of time a user can go without having to re-sign in. – thomasmichaelwallace Nov 20 '18 at 14:36
-
1Amplify have since fixed this and `Auth.currentAuthenticatedUser()` **does not** automatically refresh the session (probably because this is an expensive call). You will need to do something similar to @techie18 solution to force a refresh manually (ie not wait for 1 hour). Basically, you have to get the current session's refresh token, then pass that into `refreshSession`. – desigNerd Mar 04 '19 at 03:06
-
1How sure of this are you, considering this point in the documentation: https://aws-amplify.github.io/docs/js/authentication#managing-security-tokens "When using Authentication with AWS Amplify, you don’t need to refresh Amazon Cognito tokens manually. The tokens are automatically refreshed by the library when necessary." and this conditional in the code: https://github.com/aws-amplify/amplify-js/blob/master/packages/auth/src/Auth.ts#L895 – thomasmichaelwallace Mar 04 '19 at 11:54
-
1Disclaimer: not a amplify expert, but had to use refreshSession. We have a custom use case in our app where we need to force token refresh so that the state of the application is aware of changes in the backend. We were relying on calling `currentAuthenticatedUser` which did refresh the tokens up until a few days ago, but this does not happen anymore as accessToken jwt remained unchanged. it was only when we used refreshSession that it worked again. Also, it is not clear what’ when necessary' means. – desigNerd Mar 04 '19 at 22:58
This will hand you back an AccessToken and a idToken.
fetch("https://cognito-idp.<cognito-user-pool-region>.amazonaws.com/", {
headers: {
"X-Amz-Target": "AWSCognitoIdentityProviderService.InitiateAuth",
"Content-Type": "application/x-amz-json-1.1",
},
mode: 'cors',
cache: 'no-cache',
method: 'POST',
body: JSON.stringify({
ClientId: "<cognito-user-pool-client-id>",
AuthFlow: 'REFRESH_TOKEN_AUTH',
AuthParameters: {
REFRESH_TOKEN: "<cognito-refresh-toke>",
//SECRET_HASH: "your_secret", // In case you have configured client secret
}
}),
}).then((res) => {
return res.json(); // this will give jwt id and access tokens
});

- 349
- 1
- 3
- 5
I have used the 'amazon-cognito-identity-js' and refreshed the toke every time it expired and it solved my problem , here is a code snippet for the tricky getJwtToken part :
getJwtToken() {
if (!this.activeUser) {
return null;
}
const signInUserSession = this.activeUser.getSignInUserSession();
const idToken = signInUserSession ? signInUserSession.getIdToken() : null;
if (!idToken || idToken.getExpiration() * 1000 <= Date.now()) {
if (!signInUserSession.isValid()) {
const refreshToken = signInUserSession.getRefreshToken();
return new Promise((resolve) => {
this.activeUser.refreshSession(refreshToken, (err, session) => {
if (err) {
resolve(this.logout());
}
this.activeUser.setSignInUserSession(session);
resolve(session.getIdToken().getJwtToken());
})
});
}
return Promise.resolve(idToken.getJwtToken());
}
return Promise.resolve(idToken.getJwtToken());
}

- 639
- 8
- 19
-
2Yo have to add all the code, you have this variable "this.activeUser" is not part of the code, and you don't explain how you can resolve the problem. – Cam T Apr 17 '20 at 02:56