Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save AdnaneX/d0adc644352b5936844cc56091341bee to your computer and use it in GitHub Desktop.
Save AdnaneX/d0adc644352b5936844cc56091341bee 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: pm.environment.get('api_url'),
method: 'POST',
header: 'Content-Type:application/json',
body: {
mode: 'application/json',
raw: JSON.stringify(
{
client_id:pm.environment.get('client_id'),
client_secret:pm.environment.get('client_secret'),
grant_type:pm.environment.get('grant_type'),
grant_type:pm.environment.get('scope'),
username:pm.environment.get('username_admin'),
password:pm.environment.get('password_admin'),
})
}
};
var getToken = true;
if (!pm.environment.get('expires_in') ||
!pm.environment.get('access_token')) {
console.log('Token or expiry date are missing')
getToken = true;
} else if (pm.environment.get('expires_in') <= (new Date()).getTime()) {
console.log('Token is expired')
getToken = true;
} 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('access_token', responseJson.access_token)
var expiryDate = new Date();
expiryDate.setSeconds(expiryDate.getSeconds() + responseJson.expires_in);
pm.environment.set('expires_in', expiryDate.getTime());
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment