Skip to content

Instantly share code, notes, and snippets.

@ALTELMA
Forked from bcnzer/postman-pre-request.js
Created January 22, 2019 05:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ALTELMA/34b5b9ed2e01101800b5542e49a2be70 to your computer and use it in GitHub Desktop.
Save ALTELMA/34b5b9ed2e01101800b5542e49a2be70 to your computer and use it in GitHub Desktop.
Postman pre-request script to automatically get a bearer token from Auth0 and save it for reuse
const echoPostRequest = {
url: 'https://<my url>.auth0.com/oauth/token',
method: 'POST',
header: 'Content-Type:application/json',
body: {
mode: 'application/json',
raw: JSON.stringify(
{
client_id:'<your client ID>',
client_secret:'<your client secret>',
audience:'<my audience>',
grant_type:'client_credentials'
})
}
};
var getToken = true;
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();
pm.environment.set('currentAccessToken', responseJson.access_token)
var expiryDate = new Date();
expiryDate.setSeconds(expiryDate.getSeconds() + responseJson.expires_in);
pm.environment.set('accessTokenExpiry', expiryDate.getTime());
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment