Automate custom authentication with Postman

Behrang Saeedzadeh 28 October 2018

Postman supports a number of different authentication methods out of the box, all listed under the Authorization tab of the UI:

Postman Authorization

But what if the API you are interacting with has a custom authentication mechanism that is not supported by Postman? For example, what if you first need to obtain some sort of token from one endpoint and then pass it in the header or body of the actual endpoint you want to send a request to?

One option is to:

  • Define a helper request to obtain the token and execute it
  • Copy the returned token
  • Paste in the header/body of the actual request definition you want to execute

But this is tedious and error prone. Fortunately, Postman has a Pre-request Script feature that you can utilize to automate these steps:

Pre-request Script

Here’s some pseudo-code that shows how to obtain an authorization token from a fictitious https://token.example.com endpoint and set it as an environment variable:

const requestSpec = {
    url: 'https://token.example.com',
    method: 'POST',
    header: 'app-id:foo',
    body: {
        mode: 'raw',
        raw: JSON.stringify({
            username: 'Husky',
            password: 'W0o0f!'
        })
    }
}

pm.sendRequest(requestSpec, function(err, res) {
    if (err) {
        console.log(`Encountered an error while authenticating: ${err}`);
    } else {
        pm.environment.set('token', res.json().token);
    }
});

You can then use the token variable in your request definition and let Postman interpolate it with the value assigned to it in the pre-request script:

Upload Zommies