LOADING

Type to search

Basic Testing Postman

API Authentication Testing in Postman: OAuth 2.0, Bearer Tokens

Share

Authentication Testing Postman: OAuth 2.0, Bearer Tokens & API Key

Postman is usually the first place a tester checks an API’s authentication before any automation gets written. It is quick to set up, it shows you exactly what is being sent, and it lets you fix a broken request in seconds rather than minutes. That makes it the right starting point for all three authentication schemes you will meet most often: OAuth 2.0, Bearer tokens, and API keys.

This post covers all three, one at a time, with the exact Postman setup for each. By the end, you will have a repeatable pattern you can drop into any new collection, whatever the API in front of you happens to use.

Setting Up Your Environment First

Before touching any Authorization tab, create a Postman environment for the API under test. Store the base URL, client credentials, and any secrets there rather than typing them into individual requests. This keeps sensitive values out of your collection file and makes it trivial to switch between dev, staging, and production without editing a single request.

Environment variables (example):
baseUrl = https://api.example.com
tokenUrl = https://auth.example.com/oauth/token
clientId = {{your-client-id}}
clientSecret = {{your-client-secret}}
apiKey = {{your-api-key}}

With that in place, the token or key value never appears in plain text inside a request, only as `{{variableName}}`. Every screenshot in this post assumes that setup.

Testing OAuth 2.0 in Postman

OAuth 2.0 is the most involved of the three, since it needs a separate request just to obtain the token before your real test can run. Postman has native support for this under the Authorization tab, so you rarely need to build the token request by hand.

The mockup below walks through the full setup: the request URL, the Authorization tab, the token fields, the Tests tab, and the result.

Step-by-step mockup of testing OAuth 2.0 in Postman, showing the request URL, Authorization tab set to OAuth 2.0, token fields, Tests tab script, and the resulting 200 OK pass

Open the Authorization tab, select b, then fill in the grant type, token URL, client ID, and client secret. Click Get New Access Token, and Postman handles the handshake for you. For a repeatable collection run, though, it is worth generating the token through a script rather than a manual click, so the token becomes part of the automated flow:

javascript

// Pre-request Script: fetch and store an OAuth2 access token
pm.sendRequest({
    url: pm.environment.get("tokenUrl"),
    method: "POST",
    header: {
        "Content-Type": "application/x-www-form-urlencoded"
    },
    body: {
        mode: "urlencoded",
        urlencoded: [
            { key: "grant_type", value: "client_credentials" },
            { key: "client_id", value: pm.environment.get("clientId") },
            { key: "client_secret", value: pm.environment.get("clientSecret") }
        ]
    }
}, function (err, res) {
    if (err) {
        console.error(err);
    } else {
        const token = res.json().access_token;
        pm.environment.set("accessToken", token);
    }
});;

Set every protected request’s header to Authorization: Bearer {{accessToken}}. Because the token now lives in an environment variable, every request in the collection can reuse it without repeating the login step. Add a quick check in the Tests tab to confirm the token actually arrived:

javascript

// Tests tab
pm.test("Access token was issued", function () {
pm.expect(pm.environment.get("accessToken")).to.be.a("string").and.not.empty;
});

Finally, add one request that deliberately omits the Authorization header. A properly secured endpoint should reject it with 401, not quietly accept it. This single check catches more real security defects than almost any other test in the collection.

Testing Bearer Tokens in Postman

A Bearer token test always involves two requests: one to log in and capture the token, and one to use it. Unlike OAuth 2.0, there is no standard token endpoint, so the login request is usually a simple /login call that returns a token in the response body.

The mockup below shows both requests side by side, along with the script that passes the token from the first request to the second.

Step-by-step mockup of testing Bearer tokens in Postman, showing the login request body, the Tests tab capturing the token, and the second request using Bearer Token authorisation

On the login request, add this to the Tests tab so the token is captured automatically once the response arrives:

javascript

// Tests tab on the /login request
const response = pm.response.json();

pm.test("Login returns a token", function () {
pm.expect(response.token).to.be.a("string").and.not.empty;
});
pm.environment.set("bearerToken", response.token);

On every protected request that follows, open the Authorization tab, choose Bearer Token, and set the value to {{bearerToken}}. Postman then attaches the header automatically on send. Add a second request using a deliberately corrupted token, for example by changing one character of the JWT, and confirm the API still returns 401 rather than a server error:

javascript

// Tests tab on a request sent with a corrupted token
pm.test("Malformed token is rejected", function () {
pm.response.to.have.status(401);
});

It is worth also testing a request sent with no Authorization header at all. A well-built API should treat “missing” and “invalid” consistently, and a good test suite checks both rather than assuming they behave the same way.

Testing API Keys in Postman

API keys are the simplest scheme to test in Postman, since there is no login step and nothing expires mid-run. The main decision is where the key lives: a header, most commonly X-API-Key, or a query parameter such as ?api_key=. Postman’s API Key authorisation type lets you choose either from a single dropdown.

The mockup below shows the full setup, including how Postman applies the key differently depending on whether you choose Header or Query Params under “Add to“.

Step-by-step mockup of testing API keys in Postman, showing the Authorization tab set to API Key, header versus query parameter placement, and the Tests tab checking status and rate-limit headers

Select API Key on the Authorization tab, enter the key name and the value (ideally an environment variable, not a pasted string), and choose Header or Query Params. Then confirm the request succeeds and returns the expected rate-limit metadata:

// Tests tab: confirm a valid key returns data and includes rate-limit headers
pm.test("Valid API key returns 200", function () {
    pm.response.to.have.status(200);
});

pm.test("Rate limit headers are present", function () {
    pm.expect(pm.response.headers.has("X-RateLimit-Remaining")).to.be.true;
});

Add two more requests to round out the coverage: one with a deliberately invalid key, and one with no key at all. Check that each fails with a sensible, consistent status code:

javascript

// Tests tab on the "invalid key" request
pm.test("Invalid key returns 401, not 403", function () {
pm.response.to.have.status(401);
});

A surprising number of APIs return different codes for “invalid” versus “missing” without any real logic behind the choice. Flag this in your test report even when it is not a hard defect, since it usually points to inconsistent error handling elsewhere in the API too.

Building a Reusable Postman Collection

Once all three schemes work individually, structure your collection so the pattern is easy to reuse on the next project:

Login or token folder. Keep every request that fetches a credential in its own folder, run first, at the top of the collection.
One assertion per concern. Do not bundle “token exists” and “response shape is correct” into a single test block. Separate tests make failures easier to diagnose.
Negative-path requests live alongside their positive counterpart. Do not push them to a separate “edge cases” folder that nobody runs by default.
Use the collection runner or Newman for the full suite. Manual clicking works for exploration, but the whole point of scripting the token capture is repeatable automated runs.

Wrapping Up – API Authentication Testing in Postman

Postman handles all three authentication schemes well once you commit to scripting the token capture rather than pasting values by hand. OAuth 2.0 needs the most setup, Bearer tokens need a two-request pattern, and API keys need almost none at all. Get comfortable with all three here, and the same logic carries straight across into REST Assured and Gatling, which the next two posts in this series cover in detail.

Tags:

Leave a Comment

Your email address will not be published. Required fields are marked *