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
Refreshing a session with the amazon-cognito-identity-js browser SDK; it mostly does it for you, and unless you're doing something unusual you won't need to handle the refresh token directly. Here's what you need to know:
Assume you have instantiated the user pool like this:
const userPool = new AmazonCognitoIdentity.CognitoUserPool({
UserPoolId: USER_POOL_ID,
ClientId: USER_POOL_CLIENT_ID
});
To find the last username authenticated, you would do this:
const cognitoUser = cognitoUserPool.getCurrentUser();
If it finds one, cognitoUser will be non-null, and you can do this, which will refresh your tokens behind the scenes if needed:
cognitoUser.getSession(function(err, data) {
if (err) {
// Prompt the user to reauthenticate by hand...
} else {
const cognitoUserSession = data;
const yourIdToken = cognitoUserSession.getIdToken().jwtToken;
const yourAccessToken = cognitoUserSession.getAccessToken().jwtToken;
}
});
If you don't want these tokens persisted in local storage, you can:
cognitoUser.signOut();
The way it works is, after a successful authentication, the browser will store your JWT tokens, including that refresh token. It stores these in local storage in your browser by default, though you can provide your own storage object if you want. By default, the refresh token is valid for 30d, but it's a property (RefreshTokenValidity) of your UserPoolClient, which you can change. When you do the above, 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 do this for you, though I have not used those so can't vouch for that.