Postman Pre-Request For JWT (Auth0)

I found it incredibly annoying to need to get a new JWT and attach it to my request, so I wrote a tiny little script to get a token for me and store it in a Postman variable that will be sent along with every request in the project.

Using Postman variables, pre request and request auth setup on the project is a must.

Password Grant Type

function updateBearerToken() {
    console.log("Start - setting access token pre request");
    var domain = pm.environment.get("auth0_domain");
    var url = `https://${domain}/oauth/token`;
    console.log(url);
    pm.sendRequest({
        url: url,
        method: "POST",
        body: { 
            mode: 'urlencoded',
            urlencoded: [
            {key: "grant_type", value: "password", disabled: false},
            {key: "username", value: pm.environment.get("username"), disabled: false},
            {key: "password", value: pm.environment.get("password"), disabled: false},
            {key: "client_secret", value: pm.environment.get("client_secret"), disabled: false},
            {key: "client_id", value: pm.environment.get("client_id"), disabled: false}
            ]
        }
    }, function (err, response) {
        pm.environment.set("bearerToken", response.json().access_token);
        console.log("Done - setting access token pre request");
    });
}

var existing = pm.environment.get("bearerToken");
if (!existing) {
    updateBearerToken();
    return;
}

var pieces = existing.split('.');
if (pieces.length != 3)
{
    updateBearerToken();
    return;
}

var payload = pieces[1];
payload.replace(/-/g, '+').replace(/_/g, '/');
var jsonPayload = decodeURIComponent(atob(payload));
var parsed = JSON.parse(jsonPayload);
var currentTime = (new Date().getTime() / 1000)
if (!parsed.exp || parsed.exp < currentTime)
{
    updateBearerToken();
    return;
}


console.log("Bearer Token is still valid");

Machine to Machine

var data = {
    client_id: pm.environment.get("internal_service_client_id"),
    client_secret: pm.environment.get("internal_service_client_secret"),
    audience: pm.environment.get("internal_service_audience"),
    grant_type: "client_credentials"
};

function updateBearerToken() {
    console.log("Start - setting access token pre request");
    var domain = pm.environment.get("auth0_domain");
    var url = `https://${domain}/oauth/token`;
    console.log(url);
    console.log(data);
    pm.sendRequest({
        url: url,
        method: "POST",
        header: "content-type: application/json",
        body: { 
            mode: 'raw',
            raw: JSON.stringify(data),
        }
    }, function (err, response) {
        console.log(err, response);
        if (err) {
            console.error(err);
            return;
        }
        pm.environment.set("packages_token", response.json().access_token);
        console.log("Done - setting access token pre request");
    });
}

var existing = pm.environment.get("packages_token");
if (!existing) {
    updateBearerToken();
    return;
}

var pieces = existing.split('.');
if (pieces.length != 3)
{
    updateBearerToken();
    return;
}

var payload = pieces[1];
payload.replace(/-/g, '+').replace(/_/g, '/');
var jsonPayload = decodeURIComponent(atob(payload));
var parsed = JSON.parse(jsonPayload);
var currentTime = (new Date().getTime() / 1000)
if (!parsed.exp || parsed.exp < currentTime)
{
    updateBearerToken();
    return;
}


console.log("Bearer Token is still valid");