Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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());
}
});
}
@vuongggggg

This comment has been minimized.

Copy link

vuongggggg commented May 29, 2018

Thank you! 🗡

@alaninspace

This comment has been minimized.

Copy link

alaninspace commented May 30, 2018

Cheers!! Works well 👍

@TharinduNM

This comment has been minimized.

Copy link

TharinduNM commented Jun 7, 2018

Could you please explain how should this change for OAuth2

@NaraGitHub

This comment has been minimized.

Copy link

NaraGitHub commented Jul 10, 2018

POSTMAN : Added "Authorization: Bearer {{currentAccessToken}}", Works well

@Vallinayagam

This comment has been minimized.

Copy link

Vallinayagam commented Jul 21, 2018

Very helpful script. Thanks a lot

@Guilherme-Sensedia

This comment has been minimized.

Copy link

Guilherme-Sensedia commented Aug 14, 2018

And for generate a authorization code? I generate a POST before this call?

@testanalyst

This comment has been minimized.

Copy link

testanalyst commented Aug 21, 2018

Dear Ben,

Thanks for posting the code. May you please help me in following scenario...I first have to make an OAuth 2.0 request using my client id, secret and user credentials. That process would return a Token that I shall use as a Bearer token for all subsequent requests. In such case, we will need an extra POST for OAuth 2.0 first to get the token? How the code should be modified?

I see following code samples here and a related question (converted to Support and then Bug) here, but there is no (at least I couldn't make it) solution provided.

I think https://github.com/TharinduNM question is also on the same line. Please advise

@peternitro

This comment has been minimized.

Copy link

peternitro commented Aug 28, 2018

This is awesome, works great, thanks for sharing!

@rogerioadris

This comment has been minimized.

Copy link

rogerioadris commented Sep 22, 2018

Tanks

@SubChord

This comment has been minimized.

Copy link

SubChord commented Oct 25, 2018

Thinks simple and works like a charm

@MrNaef

This comment has been minimized.

Copy link

MrNaef commented Nov 1, 2018

Perfect, very useful.

I would use the environment or collection variables to set the , , and <my_audience>. I guess you skipped that part to to make the example more simple.

const echoPostRequest = {
  url: pm.environment.get('url') + '.auth0.com/oauth/token',
  method: 'POST',
  header: 'Content-Type:application/json',
  body: {
    mode: 'application/json',
    raw: JSON.stringify(
        {
        	client_id: pm.environment.get('your_client_id'),
        	client_secret: pm.environment.get('your client secret'),
        	audience: pm.environment.get('my_audience'),
        	grant_type:'client_credentials'
        })
  }
};
@chopinvan

This comment has been minimized.

Copy link

chopinvan commented Nov 10, 2018

Thank you

@MaiconSchuetz

This comment has been minimized.

Copy link

MaiconSchuetz commented Nov 23, 2018

Thank you!!!

@thithimos

This comment has been minimized.

Copy link

thithimos commented Dec 6, 2018

Thank you!

@tgourley

This comment has been minimized.

Copy link

tgourley commented Feb 1, 2019

FYI... my expiry string ends up being ISO format: 2019-02-01T19:36:12.569403Z

Because of this, I have to wrap the environment variable in a Date.parse(...)

if (Date.parse(pm.environment.get('accessTokenExpiry')) <= (new Date()).getTime())

@jhhwilliams

This comment has been minimized.

Copy link

jhhwilliams commented Feb 13, 2019

For endpoints that only accept x-www-form-urlencoded the request can be updated to

  url: 'https://<my url>.auth0.com/oauth/token',
  method: 'POST',
  header: 'Content-Type:application/x-www-form-urlencoded',
  body: {
            mode: 'urlencoded',
            urlencoded: [
                    { key: "client_id", value: "<your client ID>" },
                    { key: "client_secret", value: "<your client secret>" },
                    { key: "audience", value: "<my audience>" },
                    { key: "grant_type", value: "client_credentials" },
            ]
    }
};
@fubsle

This comment has been minimized.

Copy link

fubsle commented Feb 28, 2019

Thank you very much! @bcnzer @jhhwilliams

@sysqo82

This comment has been minimized.

Copy link

sysqo82 commented Jun 14, 2019

Thank you very much for this script.
Can I use one of my environment\global variables to replace my url.auth0.com?
I've tried replacing the url with {{VariableName}} but it didn't work.

Also, is there a way to skip the check for expiry date or token validity and just request a new token with every request?
Thank you.

@qw3rty

This comment has been minimized.

Copy link

qw3rty commented Jul 8, 2019

Nice script

@DeadCatEdz

This comment has been minimized.

Copy link

DeadCatEdz commented Jul 10, 2019

Thanks for the script, also thanks @jhhwilliams for the urlencoded that is required for microsoft.

From myself I was able to set the variables at the global level; though did need to add setting variables at the bottom of the script.

pm.variables.set('currentAccessToken', pm.globals.get('currentAccessToken'));

Also found that the expiry value was not working as was returned as a string, but found * 1 forced it to be an integer.

expiryDate.setSeconds(expiryDate.getSeconds() + responseJson.expires_in * 1);

Another change I made was to move the initialisation of the expiryDate variable to before the sendRequest (idea being the expiry date is then before it actually expires rather than other way round).

if (getToken === true) {
    var expiryDate = new Date();
    pm.sendRequest(echoPostRequest, function (err, res) {
@nhattan

This comment has been minimized.

Copy link

nhattan commented Jul 31, 2019

@bcnzer thank you for the nice script 💯

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.