Skip to content

Instantly share code, notes, and snippets.

@bcnzer
Last active April 23, 2024 19:26
Show Gist options
  • Save bcnzer/073f0fc0b959928b0ca2b173230c0669 to your computer and use it in GitHub Desktop.
Save bcnzer/073f0fc0b959928b0ca2b173230c0669 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());
}
});
}
@sysqo82
Copy link

sysqo82 commented Jan 27, 2023

@sayuri-sam you need to use double curly braces {{currentAccessToken}}

@bo55vxr
Copy link

bo55vxr commented Jan 27, 2023

@sayuri-sam you need to use double curly braces {{currentAccessToken}}

^^^ This...

@tester-at-bmi
Copy link

@Solksjaer thanks for the snippet just what i needed 👍

@gustavocoleta
Copy link

Tks! 👍

@troyinsight
Copy link

Hi @anantyadunath. Quick question, did you ever get auth code flow working with Postman?

@anantyadunath
Copy link

anantyadunath commented Jun 10, 2023 via email

@mahAzin
Copy link

mahAzin commented Jun 25, 2023

Hi, Do you have a solution if our authorization is with Grant Type: Authorization Code (with PKCE).
we don`t use client secret, and we put it blank.
I turn on Auto-refresh token and every API works great, but in monitor I get No response.

Screenshot 2023-06-25 122147

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