-
-
Save tester-at-bmi/ddf1ed806ae559b81d35bd39ff4f4729 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
This file contains 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://<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