Working with Cognito: AuthN

Mark Pace
Mark Pace
May 10 · 2 min read

Refreshing a User Session (Access Token)

Refreshing a session with the amazon-cognito-identity-js browser SDK; it’s mostly done for you by the SDK, and unless you’re doing something unusual you won’t need to manage the refresh token directly. Here’s what you need to know:

Assume you have instantiated the user pool like this:

To find the last user authenticated, you would do this:

If it finds a user, cognitoUser will be non-null, and you can call getSession() on cognitoUser. This will refresh your tokens behind the scenes if needed.

If you don’t want these tokens to be persisted in local storage, you can signOut():

The way it works is, after successful authentication, the browser will store the JWT tokens, including the refresh token. Cognito stores these in local storage on your browser by default, though you can provide your own storage object if you want. By default, the refresh token is valid for 30 days, but it’s a property (RefreshTokenValidity) of your UserPoolClient, which you can change.

When called cognitoUser.getSession() will first see whether the tokens you have in storage exist and are still valid; if not, it will try to use whatever refreshToken it finds there to authenticate you into a new session.

The documentation http://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-tokens-with-identity-providers.html indicates that the iOS and Android SDKs will also do this for you, though I have not used those so I don’t know empirically.

Mark Pace

Written by

Mark Pace

Solutions Architect & IoT Hackster

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade