Skip to content

Instantly share code, notes, and snippets.

@bcnzer
Last active July 22, 2024 10:59
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());
}
});
}
@Glideh
Copy link

Glideh commented Nov 26, 2021

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 a Date() multiplying it by 1000

@joelrdzdio
Copy link

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!

@abdurayimov-work
Copy link

Here is my trick:

  1. Created an environment and variable Authorization inside it.
    https://monosnap.com/file/Vn4WvhXMNsnOFPmB4sC8GU4gilfMPz

  2. 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);
});
  1. In request created inside this folder I set this header:
    https://monosnap.com/file/H0n2VnrxU1cwriJokXvlJU7I2f6qGl

  2. Each request you created inside this folder will run above script before execution:
    https://monosnap.com/file/KK3qzgDKXj27iQqlCOgdyxDFuBtl9e

@cg-at-bespokenai
Copy link

amazing!

@anantyadunath
Copy link

@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?

@MohammadAbualhasanAnati

It works perfectly! Time & Effort saving
Thanks a lot

@sayuri-sam
Copy link

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?

@bo55vxr
Copy link

bo55vxr commented Jan 26, 2023

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?

@sayuri-sam
Copy link

sayuri-sam commented Jan 27, 2023

bo55vxr
yes, I use this code as pre-request script in postman.
and I want to pass the value in currentAccessToken to Auth token.

image

the request result
image

can you figure it out?

@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