Created
September 25, 2022 17:29
-
-
Save drissamri/ecd19c394540e19d3048e243e6450a66 to your computer and use it in GitHub Desktop.
Pre-request Postman script for Cognito
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const echoPostRequest = { | |
url: 'https://cognito-idp.eu-central-1.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("USERNAME"), | |
"PASSWORD": pm.environment.get("PASSWORD") | |
}, | |
"AuthFlow": "USER_PASSWORD_AUTH", | |
"ClientId": pm.variables.get('COGNITO_CLIENT_ID') | |
}) | |
} | |
}; | |
var getToken = true; | |
if (!pm.environment.get('COGNITO_ACCESS_TOKEN_EXPIRY') || !pm.environment.get('COGNITO_ACCESS_TOKEN')) { | |
console.log('Token or expiry date are missing') | |
} else if (pm.environment.get('COGNITO_ACCESS_TOKEN_EXPIRY') <= (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') | |
var responseJson = res.json(); | |
pm.environment.set('COGNITO_ACCESS_TOKEN', responseJson.AuthenticationResult.IdToken) | |
var expiryDate = new Date(); | |
expiryDate.setSeconds(expiryDate.getSeconds() + responseJson.AuthenticationResult.ExpiresIn); | |
pm.environment.set('COGNITO_ACCESS_TOKEN_EXPIRY', expiryDate.getTime()); | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment