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());
}
});
}
@vuon9

This comment has been minimized.

Copy link

@vuon9 vuon9 commented May 29, 2018

Thank you! 🗡️

@alaninspace

This comment has been minimized.

Copy link

@alaninspace alaninspace commented May 30, 2018

Cheers!! Works well 👍

@TharinduNM

This comment has been minimized.

Copy link

@TharinduNM TharinduNM commented Jun 7, 2018

Could you please explain how should this change for OAuth2

@NaraGitHub

This comment has been minimized.

Copy link

@NaraGitHub NaraGitHub commented Jul 10, 2018

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

@Vallinayagam

This comment has been minimized.

Copy link

@Vallinayagam Vallinayagam commented Jul 21, 2018

Very helpful script. Thanks a lot

@Guilherme-Sensedia

This comment has been minimized.

Copy link

@Guilherme-Sensedia 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 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 peternitro commented Aug 28, 2018

This is awesome, works great, thanks for sharing!

@rogerioadris

This comment has been minimized.

Copy link

@rogerioadris rogerioadris commented Sep 22, 2018

Tanks

@SubChord

This comment has been minimized.

Copy link

@SubChord SubChord commented Oct 25, 2018

Thinks simple and works like a charm

@MrNaef

This comment has been minimized.

Copy link

@MrNaef 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 chopinvan commented Nov 10, 2018

Thank you

@MaiconSchuetz

This comment has been minimized.

Copy link

@MaiconSchuetz MaiconSchuetz commented Nov 23, 2018

Thank you!!!

@thithimos

This comment has been minimized.

Copy link

@thithimos thithimos commented Dec 6, 2018

Thank you!

@tgourley

This comment has been minimized.

Copy link

@tgourley 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 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 fubsle commented Feb 28, 2019

Thank you very much! @bcnzer @jhhwilliams

@sysqo82

This comment has been minimized.

Copy link

@sysqo82 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 qw3rty commented Jul 8, 2019

Nice script

@DeadCatEdz

This comment has been minimized.

Copy link

@DeadCatEdz 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 nhattan commented Jul 31, 2019

@bcnzer thank you for the nice script 💯

@ahmedtarek-

This comment has been minimized.

Copy link

@ahmedtarek- ahmedtarek- commented Nov 20, 2019

Great! Thank you!!

@morrisond91

This comment has been minimized.

Copy link

@morrisond91 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 Kenc44 commented Dec 16, 2019

Thanks @jhhwilliams for the sample urlencoded request.

@Rahul-ifourtechnolab

This comment has been minimized.

Copy link

@Rahul-ifourtechnolab Rahul-ifourtechnolab commented Jan 29, 2020

Thank you.. Works like a charm.. 👍

@Crazie-ash

This comment has been minimized.

Copy link

@Crazie-ash 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 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 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 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 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 mokkapati commented Mar 23, 2020

image
I am getting this error for urlencoded code

@DmitryVdovichencko

This comment has been minimized.

Copy link

@DmitryVdovichencko DmitryVdovichencko commented Apr 27, 2020

Thanks! So helpful nice and simple! 👍 🤘

@ultrablue

This comment has been minimized.

Copy link

@ultrablue ultrablue commented May 5, 2020

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

@aisupov

This comment has been minimized.

Copy link

@aisupov aisupov commented May 18, 2020

Thank you!

@ANHPearce

This comment has been minimized.

Copy link

@ANHPearce ANHPearce commented Jun 16, 2020

Love it

@CoreyB26

This comment has been minimized.

Copy link

@CoreyB26 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.

@chluther

This comment has been minimized.

Copy link

@chluther chluther commented Sep 2, 2020

Thank you. I've riffed off of this pattern to obtain bearer token for configuring the Akamai (Janrain) Hosted Login OIDC platform. This has been saved as a collection Pre-request Script.


// collection pre-request script
// obtain parameters from environment configuration

const uri = pm.environment.get("uri");
const customer_id = pm.environment.get("customer_id");
const config_oidc_client_id = pm.environment.get("config_client_id");
const config_oidc_client_secret = pm.environment.get("config_client_secret");
const user = btoa(pm.environment.get('config_client_id') + ':' + pm.environment.get('config_client_secret'));

const echoPostRequest = {
  url: 'https://' + uri + '/' + customer_id +'/login/token',
  method: 'POST',
  timeout: 0,
  header: {
    "Content-Type": "application/x-www-form-urlencoded",
    "Authorization": "Basic " + user
  },
  body: {
    mode: 'urlencoded',
    urlencoded: [
        {key: "grant_type", value: "client_credentials"},
        {key:"scope", value: "*:config/**"}
    ]}
};

var getToken = true;
if (!pm.environment.get('oidc_bearer_token_expiry') || 
    !pm.environment.get('oidc_bearer_token')) {
    console.log('Token or expiry date are missing')
} else if (pm.environment.get('oidc_bearer_token_expiry') <= (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) {
        var responseJson = res.json();
        console.log(responseJson);
        console.log(err ? err : responseJson);
            if ((err !== null) || (responseJson.error !== "invalid_client")) {
                console.log('Saving the token and expiry date')
                
                // save results to environment configuration
                pm.environment.set('oidc_bearer_token', responseJson.access_token)
    
                var expiryDate = new Date();
                expiryDate.setSeconds(expiryDate.getSeconds() + responseJson.expires_in);
                pm.environment.set('oidc_bearer_token_expiry', expiryDate.getTime());
            }
            else {
                console.log(err);
                console.error('Error: ' + responseJson)
            }
    });
}
@Dumbnikko

This comment has been minimized.

Copy link

@Dumbnikko Dumbnikko commented Sep 22, 2020

Thanks a bunch, helped out a newbie a lot!

@mikenhill

This comment has been minimized.

Copy link

@mikenhill mikenhill commented Oct 2, 2020

I'm not sure that the token expiry logic is working as intended. The code (below) uses expiryDate.getSeconds() which returns a value in the range 0..59 the overall result of which is to set the accessTokenExpiry variable to a value which is far in excess of the actual token expiry. What this means is that the script fails to detect when the actual token has expired and attempts to keep using an expired token.
var expiryDate = new Date();
expiryDate.setSeconds(expiryDate.getSeconds() + responseJson.expires_in);
pm.environment.set('accessTokenExpiry', expiryDate.getTime());

What I believe was intended is as follows:

var expiryDate = new Date();
expiryDate = new Date(expiryDate.getTime() + (res.json().expires_in * 1000));
console.log('expiryDate: ' + expiryDate);
pm.environment.set('accessTokenExpiry', expiryDate.getTime());

Such that when I ran this at Fri Oct 02 2020 08:57:14 GMT+0100 (British Summer Time), the expiry is set as follows:
expiryDate: Fri Oct 02 2020 09:57:14 GMT+0100 (British Summer Time)

@emads3

This comment has been minimized.

Copy link

@emads3 emads3 commented Oct 29, 2020

Thank you

@jlaguilargomez

This comment has been minimized.

Copy link

@jlaguilargomez jlaguilargomez commented Nov 12, 2020

Thanks a lot!, it seems to work!

@AdamW00d

This comment has been minimized.

Copy link

@AdamW00d AdamW00d commented Dec 3, 2020

Thank you!

@Solksjaer

This comment has been minimized.

Copy link

@Solksjaer Solksjaer commented Jan 21, 2021

I modified your code a little, in order to include a KeyCloak refresh token call using Url Encoded Forms.
Also, I included an environment validation, in order to avoid autorefresh in production.

const client_id = "client_id";
const username= "username";
const allowedEnvs = ["localEnv", "dev"]

console.log("Runing on Environment: " + pm.environment.name);

if(allowedEnvs.indexOf(pm.environment.name) == -1){
    console.warn("Token Reload only allowed on: " + allowedEnvs);
    return;
}

var keycloak_url = pm.environment.get("keycloak_url") + "/auth/realms/MY_REALM/protocol/openid-connect/token";

var access_token = pm.environment.get("access_token");
var access_token_expiry = pm.environment.get("access_token_expiry");
var refresh_token = pm.environment.get("refresh_token");
var refresh_token_expiry = pm.environment.get("refresh_token_expiry");

const refreshTokenRequest = {
  url: keycloak_url,
  method: 'POST',
  header: 'Content-Type:application/x-www-form-urlencoded',
  body: {
    mode: 'urlencoded',
    urlencoded: [
        {key: "client_id", value: client_id},
        {key: "client_secret", value: pm.environment.get("client_secret")},
        {key: "refresh_token", value: refresh_token},
        {key: "grant_type", value: 'refresh_token'}
    ]
  }
};

const newTokenRequest = {
  url: keycloak_url,
  method: 'POST',
  header: 'Content-Type:application/x-www-form-urlencoded',
  body: {
    mode: 'urlencoded',
    urlencoded: [
        {key: "client_id", value: client_id},
        {key: "client_secret", value: pm.environment.get("client_secret")},
        {key: "username", value: username},
        {key: "grant_type", value: 'password'},
        {key: "password", value: pm.environment.get("user_password")}
    ]
  }
};

var sendRequest = newTokenRequest;

if (!access_token || !access_token_expiry || 
    !refresh_token || !refresh_token_expiry) {
    console.log('Tokens or expiry dates are missing');
} else if (access_token_expiry <= (new Date()).getTime() && refresh_token_expiry <= (new Date()).getTime()) {
    console.log('Access and Refresh Token expired');
} else if (access_token_expiry <= (new Date()).getTime()) {
    console.log('Access Token expired');
    sendRequest = refreshTokenRequest;
} else {
    sendRequest = null;
    console.log('Token and expiry date are all good');
}

if (sendRequest != null) {
    pm.sendRequest(sendRequest, function (err, res) {
        var responseJson = res.json();
        console.log(err ? err : responseJson);

        if (err == null && responseJson.error == null) {
            console.log('Saving tokens and expiry dates')
            
            pm.environment.set('access_token', responseJson.access_token)
            pm.environment.set('refresh_token', responseJson.refresh_token)
    
            pm.environment.set('access_token_expiry', new Date().getTime() + (responseJson.expires_in * 1000));
            pm.environment.set('refresh_token_expiry', new Date().getTime() + (responseJson.refresh_expires_in * 1000));
        }
    });
}
@Andrielson

This comment has been minimized.

Copy link

@Andrielson Andrielson commented Mar 2, 2021

It works like a charm! Thank you!

@RodolVelasco

This comment has been minimized.

Copy link

@RodolVelasco RodolVelasco commented Mar 17, 2021

I can get the oauth2 using postman authorization form included in Authorization tab. I would like to replicate this behaviour on pre request script and do this process automatically. You have any idea? This is to connect to Azure App Registration.

@bo55vxr

This comment has been minimized.

Copy link

@bo55vxr bo55vxr commented Mar 25, 2021

@RodolVelasco

I can get the oauth2 using postman authorization form included in Authorization tab. I would like to replicate this behaviour on pre request script and do this process automatically. You have any idea? This is to connect to Azure App Registration.

I am using Azure OAuth2 tokens and basically the script is very much as described but changing the POST request.

const echoPostRequest = {
url: 'https://login.microsoftonline.com/<tenant ID>/oauth2/token','
  method: 'POST',
  body: {
    mode: 'formdata',
    formdata: [
        {key: "client_id", value:"<client ID>"},
        {key: "client_secret", value:"<client secret>"},
        {key: "resource", value:"<resource>"},
        {key: "grant_type", value:"client_credentials"}
    ]
  }
};

Hope that helps

@RodolVelasco

This comment has been minimized.

Copy link

@RodolVelasco RodolVelasco commented Mar 25, 2021

@bo55vxr thanks for your response.

I am using Azure OAuth2 tokens and basically the script is very much as described but changing the POST request.

const echoPostRequest = {
url: 'https://login.microsoftonline.com/<tenant ID>/oauth2/token','
  method: 'POST',
  body: {
    mode: 'formdata',
    formdata: [
        {key: "client_id", value:"<client ID>"},
        {key: "client_secret", value:"<client secret>"},
        {key: "resource", value:"<resource>"},
        {key: "grant_type", value:"client_credentials"}
    ]
  }
};

Hope that helps

I got it done with this script

var clientId = pm.variables.get("clientId");
var clientSecret = pm.variables.get("clientSecret");
var scope = pm.variables.get("scope");
var urlResource = pm.variables.get("urlResource");
var tenant = pm.variables.get("tenant");
var apiEndpointVersion = pm.variables.get("apiEndpointVersion");
pm.sendRequest({
    url: urlResource + tenant + apiEndpointVersion,
    method: "POST",
    header: [
        'Content-Type:application/x-www-form-urlencoded'
    ],
    body: {
        mode: "urlencoded",
        urlencoded: [
            {key: "client_id", value: clientId},
            {key: "client_secret", value: clientSecret},
            {key: "scope", value: scope},
            {key: "grant_type", value: "client_credentials"}
        ]
    },
},
(error, response) => {
    pm.variables.set("rawIdToken", response.json().access_token);
    pm.variables.set("refresh_token", response.json().refresh_token);
});

Where scope has this format:
22xxxxx-xxxx- ..../.default
Url resource is like:
https://login.microsoftonline.com/
apiEndpointVersion is:
/oauth2/v2.0/token
And the other variables are just their values.

@lukw4l

This comment has been minimized.

Copy link

@lukw4l lukw4l commented Apr 7, 2021

This is awesome and works like a charm, thank you very much!
I modified the script a bit (used environment variables as input and a urlencoded body) but this script was a very good starting point for further development.

@beliar91

This comment has been minimized.

Copy link

@beliar91 beliar91 commented May 11, 2021

This is super useful thank you! That's the exact thing I was looking for, helped me out a lot :).

@jcgaza

This comment has been minimized.

Copy link

@jcgaza jcgaza commented May 15, 2021

Hi, how do I add custom permissions on this script? I keep on getting an Insufficient Scope error on mine because I have permissions setup on my routes.

@tboulord

This comment has been minimized.

Copy link

@tboulord tboulord commented Jul 2, 2021

Thank you, perfectly solve my issue (Just had to adapt with urlencoded mode to fit with Keycloack)

@DanielLaberge

This comment has been minimized.

Copy link

@DanielLaberge DanielLaberge commented Jul 16, 2021

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

@deniswou

This comment has been minimized.

Copy link

@deniswou deniswou commented Jul 20, 2021

Thank you very much, it helped me a lot

@grempe

This comment has been minimized.

Copy link

@grempe grempe commented Jul 28, 2021

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());
        }
    });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment