Postman allows us to specify an OAuth2.0 flow to get a JWT from the AWS Cognito user pool, but by default, it will use the access_token, and sometimes you need to use the custom attributes included in the id_token.

This post will help us automate getting the Cognito JWT id_token by using a pre-request script in postman.

The following pre-request script will:

• Validate if we want to refresh the token on every request. If not, it will use the stored token from a previous request
• Validate if the token is still valid by verifying the expiry timestamp.
• If the token is not good, it will request a new one and store it in an environment variable.
• If the token is still valid, it will simply reuse it for the request.

Source available on gist

const echoPostRequest = {
url: 'https://cognito-idp.us-west-2.amazonaws.com/',
method: 'POST',
'Content-Type' : 'application/x-amz-json-1.1',
'X-Amz-Target': 'AWSCognitoIdentityProviderService.InitiateAuth'
},
body: {
mode: 'application/json',
raw: JSON.stringify(
{
"AuthParameters" : {
},
"ClientId" : pm.environment.get('cognitoPoolClientId')
})
}
};

var fetchTokenOnEveryRequest = pm.environment.get('fetchTokenOnEveryRequest') ? (pm.environment.get('fetchTokenOnEveryRequest')==='true'):false;

var getToken = true;

if(!fetchTokenOnEveryRequest){
console.log('removing previous token')
pm.environment.unset('accessTokenExpiry')
}
if (!pm.environment.get('accessTokenExpiry') ||
!pm.environment.get('currentAccessToken')) {
console.log('Token or expiry date are missing')
} else if (pm.environment.get('accessTokenExpiry') <= (new Date()).getTime()) {
console.log('Token is expired')
} else {
getToken = false;
console.log('Token and expiry date are all good');
}

if (getToken === true) {
pm.sendRequest(echoPostRequest, function (err, res) {
console.log(err ? err : res.json());
if (err === null) {
console.log('Saving the token and expiry date')
var responseJson = res.json();
console.log(responseJson.AuthenticationResult.ExpiresIn)
pm.environment.set('currentAccessToken', responseJson.AuthenticationResult.IdToken)
if(fetchTokenOnEveryRequest){
var expiryDate = new Date();
expiryDate.setSeconds(expiryDate.getSeconds() + responseJson.AuthenticationResult.ExpiresIn);
pm.environment.set('accessTokenExpiry', expiryDate.getTime());
}
}
});
}

### Required environment variables

The following variables are required to fetch the tokens:

Variable Example Description
cognitoPoolClientId 123435356578 Your cognito user pool clientId
fetchTokenOnEveryRequest* true/false Specify if you want to fetch a new token on every request. By setting it to true it will remove the accessTokenExpiry variable from the environment.

fetchTokenOnEveryRequest Is optional, it will default to false if is not specified

Once you add the script and the variables, you'll be able to perform your requests and, if fetchTokenOnEveryRequest is set to false, you'll see a couple of variables holding the data of the last token:

Variable Description
currentAccessToken Previously generated token
accessTokenExpiry Timestamp with the token expiry

Ensure to set {{currentAccessToken}} as a Bearer value in the authorization tab.

Update: 01/18/2022

I've fixed a wrong condition to save the expiry date