Automatically generating authentication tokens using Postman

Postman is awesome. It does lots of magic things that most people don’t know about or even care about.

One of the useful features if you’re working with API’s that use frequently expiring tokens (such as short lived JWT’s) then you may be making a request to get a fresh JWT & manually copying + pasting this into a separate postman requests.

This can be easily automated by utilising the Pre-Request Scripts feature & global variables. By adding a short script on to a collections Pre-Request, we can ensure that every request gets a valid Authorization header added on.

The magic

In every request, we’ll need to add a dummy Authorization header referencing our variable containing the valid JWT Authorization, {auth-value}

var token = pm.variables.get("auth-value")

var tokenValid;

if (token) {
    var jwt = parseJwt(token);

    var dateNow = new Date();

    if (jwt.exp < dateNow.getTime()) {
        tokenValid = false;
    } else {
        tokenValid = true;
    }
}

if (tokenValid) {
    console.log("token is valid")
    return;
}

pm.sendRequest({
    url: 'http://api.awesomesite.net/v1/authorization/',
    method: 'POST',
    header: {
        'content-type': 'application/x-www-form-urlencoded'
    },
    body: {
        mode: 'urlencoded',
        // Pass in your values to generate a token here:
        urlencoded: [
            { key: "UserName", value: "stephen.baker@bananafinance.co.uk" },
            { key: "Password", value: "supersecret" }
        ]
    }
}, function (err, res) {
    if (!err){
        console.log("setting token", res.json().authenticationToken)
        postman.setGlobalVariable("auth-token", res.json().authenticationToken);
    } else {
        console.error(err);
    }
});

function parseJwt (token) {
    var base64Url = token.split('.')[1];
    var base64 = base64Url.replace('-', '+').replace('_', '/');
    return JSON.parse(atob(base64));
};


Postman also has a console so if there’s any issues with this script or any other nifty scripts you may find or create, it’s easy to debug them (the console can be found in the bottom left corner or you can press Ctrl+Alt+C)