-
-
Save bcnzer/073f0fc0b959928b0ca2b173230c0669 to your computer and use it in GitHub Desktop.
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()); | |
} | |
}); | |
} |
For anyone wanting to use an id_token instead of an access_token, I've adapted this script to talk with AWS Cognito User Pools to exchange a refresh_token for an id_token and access_token. You could use it with most OAuth2 endpoints, not just Cognito.
https://gist.github.com/DanielLaberge/5c311b7adb835efc004fcc8e1ea7822a
Thanks for the original script, @bcnzer
Thank you very much, it helped me a lot
Here's a minor tweak on the Auth0 script that makes use of four environment specific variables you can set. This is useful if you are testing multiple environments, each with different Auth0 credentials. Only the echoPostRequest
section is modified.
You'll need to set auth0_domain
, auth0_client_id
, auth0_client_secret
, auth0_audience
variables.
const echoPostRequest = {
url: `https://${pm.environment.get('auth0_domain')}/oauth/token`,
method: 'POST',
header: 'Content-Type:application/json',
body: {
mode: 'application/json',
raw: JSON.stringify(
{
"client_id": pm.environment.get('auth0_client_id'),
"client_secret": pm.environment.get('auth0_client_secret'),
"audience": pm.environment.get('auth0_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();
console.log(responseJson.access_token)
pm.environment.set('currentAccessToken', responseJson.access_token)
var expiryDate = new Date();
expiryDate.setSeconds(expiryDate.getSeconds() + responseJson.expires_in);
pm.environment.set('accessTokenExpiry', expiryDate.getTime());
}
});
}
Nice! Thank you!!!
Good script, thx all.
One can also get the expiry from the token (if not returned explicitly by the API):
const payload = JSON.parse(atob(responseJson.access_token.split('.')[1]));
console.log(new Date(payload.exp * 1000));
Details:
- Split the token by '.'
- Take the payload (second element between [0]: header and [2]: signature)
- Base 64 decode the string with
atob()
JSON.parse()
the decoded payload- Expiration timestamp can be found in the
exp
key - Eventually
exp
can be converted to aDate()
multiplying it by 1000
Very nice, I was struggling trying to do something like this, and then decided to search and see if anybody had done it already. Found it and it works great. Thank you!
Here is my trick:
-
Created an environment and variable
Authorization
inside it.
https://monosnap.com/file/Vn4WvhXMNsnOFPmB4sC8GU4gilfMPz -
Added a folder called "User". In folder settings I defined pre-request:
https://monosnap.com/file/AWMMTcSs6TtJw3Eqet3gMBLmOdcDA5
pm.sendRequest({
url: 'https://' + pm.variables.get('api_domain') + '/api/auth/login',
method: 'POST',
header: {
'content-type': 'application/json',
},
body: {
mode: 'raw',
raw: JSON.stringify({
email: pm.variables.get('admin_email'),
password: pm.variables.get('admin_password'),
captcha_token: "no_for_local"
})
}
}, function (err, res) {
pm.environment.set("Authorization", "Bearer " + res.json().token);
});
-
In request created inside this folder I set this header:
https://monosnap.com/file/H0n2VnrxU1cwriJokXvlJU7I2f6qGl -
Each request you created inside this folder will run above script before execution:
https://monosnap.com/file/KK3qzgDKXj27iQqlCOgdyxDFuBtl9e
amazing!
@bcnzer - I am trying to figure out if similar script could work for auth code flow. I need user to sign in, based on which need to generate the access token. Unfortunately, postman "Authorization" tab does not expose the access_token as variable and they are still working on it (since long 4 years). Have you ever faced this situation? Do you have any workarounds in mind?
It works perfectly! Time & Effort saving
Thanks a lot
thx a lot,
I use it in postman pre-request script but unfortunately I couldn't pass the currentAccessToken to the second request
how to do it?
thx a lot, I use it in postman pre-request script but unfortunately I couldn't pass the currentAccessToken to the second request how to do it?
@sayuri-sam What do you mean, 2nd request? Have you specified the currentAccessToken
as a variable in the Authorization tab of the request?
bo55vxr
yes, I use this code as pre-request script in postman.
and I want to pass the value in currentAccessToken to Auth token.
can you figure it out?
@sayuri-sam you need to use double curly braces {{currentAccessToken}}
@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?
Thank you, perfectly solve my issue (Just had to adapt with urlencoded mode to fit with Keycloack)