Go to Blog

Automatically generating authentication tokens using Postman

postmantoolshttpjwt

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 Collection's Pre-Request, we can ensure that every request gets a valid Authorization header added on.

Pre-Request script

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: "[email protected]" },
            { 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));
};

This can either be copied into individual Postman requests or onto a Folder / Collection to avoid duplication

Console

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)

Enjoy my content? Want to buy me some snacks and support this hungry developer?
Buy Me A Coffee
Go to Blog
© Steve Baker 2021, Built using Gatsby. Last updated: 6/20/2021