How to refresh AWS Cognito user pool tokens for SSO

In this blog, I am going to explain how to get the id and access tokens using Cognito refresh token from the browser.

Cognito user pool is an AWS user identity service which is implemented using the OpenID Connect (OIDC) standard so it gives the following three token upon successful authentication:

  • ID Token contains details about the user attributes and can be used as an authorizer in AWS API gateway service.
  • Access Token authorizes to Cognito user pool APIs for updating user profile or signing them out on their behalf.
  • Refresh Token is for refreshing the above two tokens. The ID and access tokens are valid only for an hour but refresh token validity is configurable.
Source: https://amzn.to/2fo77UI

What is Single Sign-On (SSO)?

SSO is where you ask your end customer to sign in once and store the authentication result in the browser session using local storage or cookies and then reuse the session information for multiple apps without asking them to sign in again.

We have implemented SSO using AWS Amplify where one application provides a login to Cognito user pool and other apps call the login app when a user needs to be authenticated and the login app redirects the calling app with the token when the user is successfully authenticated. AWS Amplify provides a nice wrapper on top Cognito user pool APIs and makes it easy to integrate web apps with Cognito User pool. AWS amplify automatically refresh the tokens but doesn’t provide any way to fetch new tokens using just refresh token so we couldn’t implement self-refreshing of Id and access tokens in the apps without calling the login app every time using AWS Amplify.

I started researching further to find another way and I found a Cognito user pool API: InitiateAuth which can help with our requirement but when we tried to invoke the API using AWS Javascript SDK, it was asking to provide AWS credentials but we need to call this API from WebApp using refresh token and there are no AWS credentials in that context. We got stuck and I started digging into AWS Amplify and found that we can call the rest API directly using node-fetch without using AWS SDK. I am sharing the below code so that you can save a day.

Conclusion

This is a very small blog on how to refresh Cognito user pool tokens using refresh token from a web app but I hope this is helpful to you.