Skip to content

Instantly share code, notes, and snippets.

@DanielLaberge
Forked from bcnzer/postman-pre-request.js
Last active April 3, 2024 18:58
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DanielLaberge/5c311b7adb835efc004fcc8e1ea7822a to your computer and use it in GitHub Desktop.
Save DanielLaberge/5c311b7adb835efc004fcc8e1ea7822a to your computer and use it in GitHub Desktop.
Postman pre-request script to automatically get an id_token from AWS Cognito using a Refresh Token and save it for reuse
/* This Postman pre-request script allows using an id_token from an Amazon Cognito OAuth2 flow instead of the access_token.
It only exists as a workaround because Postman's team has been ignoring requests to let us use an id_token instead of access_token since 2014.
See: https://github.com/postmanlabs/postman-app-support/issues/8231 and https://github.com/postmanlabs/postman-app-support/issues/492
It has been adapted to support AWS Cognito User Pools from https://gist.github.com/bcnzer/073f0fc0b959928b0ca2b173230c0669#file-postman-pre-request-js-L29
It uses a refresh_token (which you must get manually) and exchanges it for an id_token, and refreshes it automatically as needed.
You could use it to talk to most OAuth2 Endpoints with very minimal changes.
How to use:
1- Set your Collection Authorization type to "Bearer Token" using this value: {{_current_id_token}}
Your Requests should be set to 'Inherit auth from parent'
2- Copy this script into your Collection Pre-request Script.
3- Set the following variables in your collection, or/and in your environments as required by your use-case:
The examples supplied here are for AWS Cognito
- OAuth2BaseUrl: Your Amazon Cognito domain. eg: https://<your-domain-prefix>.auth.us-east-1.amazoncognito.com
- OAuth2ClientId: Your Cognito App client id
- OAuth2RefreshToken: You can get this by using the LOGIN or AUTHORIZATION endpoints as defined in https://docs.aws.amazon.com/cognito/latest/developerguide/login-endpoint.html
For our use-case, we copy the refresh_token from our existing application, which expires and must be re-entered after x weeks.
*/
// Get your Refresh Token from Takeoff's Local Storage and put it in this collection's Variables as OAuth2RefreshToken, in the Current Value Column (NOT INITIAL VALUE; THAT IS SYNCED ACROSS THE TEAM).
var url = pm.variables.get('OAuth2BaseUrl') + "/oauth2/token"; // https://docs.aws.amazon.com/cognito/latest/developerguide/token-endpoint.html
var clientId = pm.variables.get('OAuth2ClientId');
var refresh_token = pm.variables.get('OAuth2RefreshToken');
const echoPostRequest = {
url: url,
method: "POST",
header: [
'Content-Type:application/x-www-form-urlencoded'
],
body: {
mode: "urlencoded",
urlencoded: [
{key: "grant_type", value: "refresh_token"},
{key: "client_id", value: clientId},
{key: "refresh_token", value: refresh_token}
]
},
};
if (!pm.variables.get('_current_id_token') || !pm.environment.has('_current_id_token_expires_at') || pm.environment.get('_current_id_token_expires_at') < (new Date()).getTime()) {
console.info('id_token missing or expired, getting new one from: ' + url)
pm.sendRequest(echoPostRequest, function (err, res) {
if (err) {
console.log(err);
console.error("Could not get id_token. Your OAuth2RefreshToken may be expired or invalid.")
} else {
console.log('Success. Saving the id_token')
var responseJson = res.json();
var expiryDate = new Date();
expiryDate.setSeconds(expiryDate.getSeconds() + responseJson.expires_in);
pm.environment.set('_current_id_token', responseJson.id_token)
pm.environment.set('_current_id_token_expires_at', expiryDate.getTime())
}
});
}
@mevansLA
Copy link

mevansLA commented Aug 13, 2021

Was having an issue with an invalid refresh token (line return at the end of the variable). Took a while to track down, I suggest updating line 51-52 with the following:

        if (err || res.code != 200) { 
            if(!err)
                console.log(res.status);
            else
                console.log(err);

@semlak
Copy link

semlak commented Aug 17, 2022

@mevansLA I made same change.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment