Question:
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.
Answer:
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:
1 2 3 4 5 6 |
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.