I am using Cognito user pool to authenticate users in my system. A successful authentication gives an ID Token (JWT), Access Token (JWT) and a Refresh Token. The documentation here, clearly mentions that the refresh token can be used to refresh access token, but does not mention how. My question is once my Access Token expires, how do I use the stored refresh token to refresh my access token again?
I searched through the JavaScript SDK and could not find any method to do the same. I definitely missed something.
Also I was thinking to do this via a Lambda function which takes in the access token and refresh token and responds with a refreshed access token. Would be great if anyone can throw some light on this.
If you're in a situation where the Cognito Javascript SDK isn't going to work for your purposes, you can still see how it handles the refresh process in the SDK source:
You can see in refreshSession
that the Cognito InitiateAuth endpoint is called with REFRESH_TOKEN_AUTH
set for the AuthFlow
value, and an object passed in as the AuthParameters
value.
That object will need to be configured to suit the needs of your User Pool. Specifically, you may have to pass in your SECRET_HASH
if your targeted App client id has an associated App client secret. User Pool Client Apps created for use with the Javascript SDK currently can't contain a client secret, and thus a SECRET_HASH
isn't required to connect with them.
Another caveat that might throw you for a loop is if your User Pool is set to remember devices, and you don't pass in the DEVICE_KEY
along with your REFRESH_TOKEN
. The Cognito API currently returns an "Invalid Refresh Token" error if you are passing in the RefreshToken
without also passing in your DeviceKey
. This error is returned even if you are passing in a valid RefreshToken
. The thread linked above illuminates that, though I do hope AWS updates their error handling to be less cryptic in the future.
As discussed in that thread, if you are using AdminInitiateAuth along with ADMIN_NO_SRP_AUTH
, your successful authentication response payload does not currently contain NewDeviceMetadata
; which means you won't have any DeviceKey
to pass in as you attempt to refresh your tokens.
My app calls for implementation in Python, so here's an example that worked for me:
def refresh_token(self, username, refresh_token):
try:
return client.initiate_auth(
ClientId=self.client_id,
AuthFlow='REFRESH_TOKEN_AUTH',
AuthParameters={
'REFRESH_TOKEN': refresh_token,
'SECRET_HASH': self.get_secret_hash(username)
# Note that SECRET_HASH is missing from JSDK
# Note also that DEVICE_KEY is missing from my example
}
)
except botocore.exceptions.ClientError as e:
return e.response