Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Automating Authentication for Postman Requests/Collection

For this doc we will automate authentication(OAuth2 Password Grant) for all requests in a Postman Collection. This will:

Automatically obtain and refresh an OAuth2 access token using the Password Grant flow before each API request, ensuring a valid token is always used.


Uses Postman Concepts

  • Pre-request Script: Runs automatically before every request in the collection (if set at collection level).
  • Environment Variables: Store dynamic data like tokens, timestamps, URLs, credentials, and expiration times.

In script below we evaluate:

  • Variable Nesting: Use pm.variables.replaceIn() to resolve variables inside other variables (e.g., Auth_Url containing {{endpoint}}).

Environment Variables Used (set these in your Environment)

VariablePurposeExample Value
endpointBase URL and port of the auth server172.16.109.57:32701
Auth_UrlFull token URL, referencing {{endpoint}}http://{{endpoint}}/auth/realms/cloud/protocol/openid-connect/token
Client_IdOAuth2 client IDclient_id
UsernameUsername for password grantparth2@coredge.io
PasswordPassword for password grantadmin
OAuth_TokenStores current access token(set dynamically by script)
OAuth_TimestampTimestamp of when token was obtained(set dynamically by script)
ExpiresInTimeToken validity duration in milliseconds(set dynamically or default 300000 ms = 5 min)

How the below Pre-request Script Works

  1. Check for valid token: Compares current time with OAuth_Timestamp plus ExpiresInTime. If token is valid and present, skips refresh.

  2. Resolve nested variables: Uses pm.variables.replaceIn() to replace {{endpoint}} in Auth_Url.

  3. Make token request: Sends a POST request to the OAuth2 token endpoint using password grant. Sends URL-encoded form data: grant_type, client_id, username, password, optionally scope.

  4. Handle response: On success, saves new access token and timestamp. Updates ExpiresInTime based on token expiry from the response.

  5. Logs: Helpful console messages for debugging token refresh status.

Copy the script to your postman Collection:

// Default expiration time to 5 minutes (in ms)
const DEFAULT_EXPIRES_IN = 300000;

// Retrieve token timestamp and expiration time from environment
const expiresInTime = Number(pm.environment.get("ExpiresInTime")) || DEFAULT_EXPIRES_IN;
const tokenTimestamp = Date.parse(pm.environment.get("OAuth_Timestamp") || 0);

// Check if token is expired or missing
if ((new Date() - tokenTimestamp) < expiresInTime && pm.environment.get("OAuth_Token")) {
    // Token is still valid; no need to refresh
    console.log("Access token still valid, skipping refresh.");
    return;
}

console.log("Access token expired or missing, requesting a new token...");

// Resolve Auth URL with nested {{endpoint}} variable
const rawAuthUrl = pm.environment.get("Auth_Url");
const authUrl = pm.variables.replaceIn(rawAuthUrl);

// Prepare OAuth request payload
const clientId = pm.environment.get("Client_Id");
const username = pm.environment.get("Username");
const password = pm.environment.get("Password");
const scope = pm.environment.get("Scope") || "";

pm.sendRequest({
    url: authUrl,
    method: "POST",
    header: {
        "Content-Type": "application/x-www-form-urlencoded"
    },
    body: {
        mode: "urlencoded",
        urlencoded: [
            { key: "grant_type", value: "password" },
            { key: "client_id", value: clientId },
            { key: "username", value: username },
            { key: "password", value: password },
            // Only include scope if it's set
            ...(scope ? [{ key: "scope", value: scope }] : [])
        ]
    }
}, function (err, res) {
    if (err) {
        console.error("Error while fetching access token:", err);
        return;
    }

    if (res.code !== 200) {
        console.error(`Token request failed with status ${res.code}:`, res.text());
        return;
    }

    const json = res.json();
    pm.environment.set("OAuth_Token", json.access_token);
    pm.environment.set("OAuth_Timestamp", new Date());

    if (json.expires_in) {
        pm.environment.set("ExpiresInTime", json.expires_in * 1000);
    }

    console.log("New access token obtained and saved.");
});


Final: Using the above setup with Requests

Here’s a step-by-step guide to set up collection-level Authorization in Postman using {{OAuth_Token}} we create in above script:


Step 1: Open your Collection settings

  • In Postman sidebar, find your collection.
  • Click the three dots (•••) next to the collection name.
  • Select Edit.

Step 1: Collection Edit


Step 2: Go to the Authorization tab

  • In the Edit Collection modal, click the Authorization tab.

Step 2: Authorization Tab


Step 3: Set Type to Bearer Token

  • Click the Type dropdown.
  • Select Bearer Token.

Step 3: Select Bearer Token


Step 4: Enter {{OAuth_Token}} as Token value

  • In the Token field, enter:
{{OAuth_Token}}

Step 4: Enter Token


Step 5: Save your changes

  • Click Save at the bottom right of the modal.

Step 6: Verify requests inherit Authorization

  • Open any request in the collection.
  • Go to its Authorization tab.
  • It should show Inherit auth from parent.

Step 6: Request inherits Authorization


Done!

Now every request in your collection will send the header:

Authorization: Bearer <your-current-OAuth-token-from-environment>

and your pre-request script ensures {{OAuth_Token}} is always fresh.





References:


< Go to Home >