Skip to content

Instantly share code, notes, and snippets.

@rcarrillodev
Last active January 19, 2022 00:10
Show Gist options
  • Save rcarrillodev/ba395e54876ed61a9794e6684d1858df to your computer and use it in GitHub Desktop.
Save rcarrillodev/ba395e54876ed61a9794e6684d1858df to your computer and use it in GitHub Desktop.
Postman pre-request script to fetch jwt tokens from cognito
const echoPostRequest = {
url: 'https://cognito-idp.us-west-2.amazonaws.com/',
method: 'POST',
header: {
'Content-Type' : 'application/x-amz-json-1.1',
'X-Amz-Target': 'AWSCognitoIdentityProviderService.InitiateAuth'
},
body: {
mode: 'application/json',
raw: JSON.stringify(
{
"AuthParameters" : {
"USERNAME" : pm.environment.get('credentialsUsername'),
"PASSWORD" : pm.environment.get('credentialsPassword')
},
"AuthFlow" : "USER_PASSWORD_AUTH",
"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());
}
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment