Last active
July 22, 2024 10:59
-
-
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
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()); | |
} | |
}); | |
} |
@sayuri-sam you need to use double curly braces
{{currentAccessToken}}
^^^ This...
@Solksjaer thanks for the snippet just what i needed 👍
Tks! 👍
Hi @anantyadunath. Quick question, did you ever get auth code flow working with Postman?
Unfortunately, nope. I was supposed to use this for Automation testing, however dropped the research since something different came up. But do post your method if you are successful.Thanks and Regards,Anant KulkarniOn 09-Jun-2023, at 11:39 AM, Troy Holland ***@***.***> wrote:Re: ***@***.*** commented on this gist.Hi @anantyadunath. Quick question, did you ever get auth code flow working with Postman?—Reply to this email directly, view it on GitHub or unsubscribe.You are receiving this email because you were mentioned.Triage notifications on the go with GitHub Mobile for iOS or Android.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@sayuri-sam you need to use double curly braces
{{currentAccessToken}}