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 💯

@ahmedtarek-

This comment has been minimized.

Copy link

ahmedtarek- commented Nov 20, 2019

Great! Thank you!!

@morrisond91

This comment has been minimized.

Copy link

morrisond91 commented Dec 11, 2019

Maybe a noob question, but is it possible to do something like this using authorisation_code grant type?

@Kenc44

This comment has been minimized.

Copy link

Kenc44 commented Dec 16, 2019

Thanks @jhhwilliams for the sample urlencoded request.

@Rahul-ifourtechnolab

This comment has been minimized.

Copy link

Rahul-ifourtechnolab commented Jan 29, 2020

Thank you.. Works like a charm.. 👍

@Crazie-ash

This comment has been minimized.

Copy link

Crazie-ash commented Feb 4, 2020

I did the same but with the grant type "authorization_code", and the header's including url encoded type and authorization with encryted client details as Basic "". it returns grant type missing required parameters. I compared the request in the console for the one I clicked manually. I came to know that I am missing a parameter "code". But I don't know where it comes from and it changes every time I click the request new token. Little help required here. Can anyone make me clear what to do? I am testing it with imgur...

@jhhwilliams

This comment has been minimized.

Copy link

jhhwilliams commented Feb 5, 2020

@Crazie-ash, I'm not sure about imgur's implementation but, using the authorization_code grant type, usually you would need 2 steps to acquire an access token:

  1. /authorize endpoint with client_id, client_secret, response_type = code and any other relevant parameters *note that this step requires user input
  2. /token endpoint with client_id, grant_type = authorization_code, code (which you received in 1.) and any other relevant parameters

See this for more information.

Postman has built-in OAuth2.0 functionality which renders the UI needed for user input
image

@sygibson

This comment has been minimized.

Copy link

sygibson commented Feb 24, 2020

This is a fantastic starting point that helped me to solve a similar problem. If anyone needs to acquire a JWT Token from a Digital Rebar Platform endpoint, the following Pre-request Script code should work:

//
// Makes API call with Basic auth to get a JWT Token from the DRP Endpoint
//
// REQUIRES:   RS_ENDPOINT set in Postman Variables
// OPTIONAL:   RS_USERNAME, RS_PASSWORD, and RS_TOKEN_DURATION Variables
// DEBUGGING:  Set RS_DEBUG_ENABLE to true, to output debug Postman console info
//

//
// These need to be set in a Postman Environment or Global variables to access your DRP
// Endpoint via correct Username/Password to acquire your token.  The duration
// should be set to something like 600 (seconds), and will renew once it expires.
// If username/password/duration not specified, we will default to the product defaults.
// Postman Variable "RS_TOKEN" will be set with the token for use in Auth Bearer type.
//
var getToken = true
const moment = require('moment')

if (!_.has(pm.environment.toObject(), 'AccessTokenExpiry') 
    || !_.has(pm.environment.toObject(), 'RS_TOKEN')
    || pm.environment.get('AccessTokenExpiry') <= moment().valueOf()) {
} else {
    getToken = false
}

if (getToken) {
    const ENDPOINT = pm.environment.get("RS_ENDPOINT");
    const USER = pm.environment.get("RS_USERNAME") ||'rocketskates';
    const PASS = pm.environment.get("RS_PASSWORD") || 'r0cketsk8ts';
    const SECS = pm.environment.get("RS_TOKEN_DURATION") || '600';
    const DBG = pm.environment.get("RS_DEBUG_ENABLE") || false;

    if (DBG) {
        console.log("DEBUGGING OUTPUT:")
        console.log("endpoint:" + ENDPOINT)
        console.log("username:" + USER)
        console.log("password:" + PASS)
        console.log("token seconds:" + SECS)
    }

    const BASIC = btoa(USER + ':' + PASS);
    const tokenDurationMS =  SECS * 1000;

    const getRSTOKEN = {
       url: `${ENDPOINT}/api/v3/users/${USER}/token?ttl=${tokenDurationMS}`,
       method: 'GET',
        header: {
           Authorization: `Basic ${BASIC}`
        }
    }    
    
    pm.sendRequest(getRSTOKEN, (err, res) => {
        if (err === null) {
            pm.environment.set('RS_TOKEN', res.json().Token)
            pm.environment.set('AccessTokenExpiry', moment().valueOf() + SECS)
        }
    })
}
@guiljs

This comment has been minimized.

Copy link

guiljs commented Mar 20, 2020

@Crazie-ash, I'm not sure about imgur's implementation but, using the authorization_code grant type, usually you would need 2 steps to acquire an access token:

  1. /authorize endpoint with client_id, client_secret, response_type = code and any other relevant parameters *note that this step requires user input
  2. /token endpoint with client_id, grant_type = authorization_code, code (which you received in 1.) and any other relevant parameters

See this for more information.

Postman has built-in OAuth2.0 functionality which renders the UI needed for user input
image

Excellent. Pretty easy to configure.

@mokkapati

This comment has been minimized.

Copy link

mokkapati commented Mar 23, 2020

How to set the environment variables or setup environment for the above urlencoded code. I am getting 500 error.

@mokkapati

This comment has been minimized.

Copy link

mokkapati commented Mar 23, 2020

image
I am getting this error for urlencoded code

@DmitryVdovichencko

This comment has been minimized.

Copy link

DmitryVdovichencko commented Apr 27, 2020

Thanks! So helpful nice and simple! 👍 🤘

@ultrablue

This comment has been minimized.

Copy link

ultrablue commented May 5, 2020

Sooooooo helpful and sanity-saving. Thank you!!!

@aisupov

This comment has been minimized.

Copy link

aisupov commented May 18, 2020

Thank you!

@ANHPearce

This comment has been minimized.

Copy link

ANHPearce commented Jun 16, 2020

Love it

@CoreyB26

This comment has been minimized.

Copy link

CoreyB26 commented Jul 23, 2020

Works perfectly! I am running Postman in a CI pipeline and needed to be able to get the token automatically and the built in Authentication didn't seem to support that. Thank you for this simple implementation.

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.