π‘οΈ Delegated Identity, Interactive Consent & Cryptographic PKCE Defenses
While machine-to-machine APIs rely on direct credentials, consumer-facing applications require delegated authorization where users grant permissions without exposing plaintext credentials to third parties. The OAuth 2.0 Authorization Code Grant (RFC 6749 Β§4.1) is the industry standard for this flow, complemented by Proof Key for Code Exchange (PKCE, RFC 7636) to secure single-page and native applications against authorization code interception attacks. In Postman, testing this flow spans two distinct domains: an interactive desktop integration using Postmanβs embedded OAuth 2.0 browser helper and callback URL (https://oauth.pstmn.io/v1/callback), and a headless automated pipeline for CI/CD runners (like Newman) where Pre-request scripts synthesize high-entropy code verifiers, compute SHA-256 code challenges, exchange authorization codes via pm.sendRequest(), and handle background token refreshes without user intervention.
AUTHORIZATION CODE FLOW WITH PKCE (PROOF KEY FOR CODE EXCHANGE):
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β 1. CLIENT CRYPTOGRAPHIC PREPARATION (Pre-request Script / Postman Engine) β
β - Generate Code Verifier: 128 high-entropy characters [A-Z, a-z, 0-9, -, ., _, ~] β
β - Compute Code Challenge: BASE64URL(SHA256(Code Verifier)) β
β - Generate Cryptographic State Nonce: UUID / Hex string (CSRF Defense) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ (Browser / User Agent Redirect)
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β 2. AUTHORIZATION REQUEST: GET /oauth/authorize β
β ?response_type=code β
β &client_id={{clientId}} β
β &redirect_uri=https://oauth.pstmn.io/v1/callback β
β &scope=students:read%20students:write β
β &state={{stateNonce}} β
β &code_challenge={{codeChallenge}} β
β &code_challenge_method=S256 β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ (User authenticates & consents)
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β 3. AUTHORIZATION CODE REDIRECT CALLBACK: HTTP 302 Found β
β Location: https://oauth.pstmn.io/v1/callback?code=AUTH_CODE_XYZ123&state={{stateNonce}} β
β - Verification: Client asserts returned state matches original {{stateNonce}} β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ (Backend Machine-to-Machine POST)
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β 4. TOKEN REDEMPTION REQUEST: POST /oauth/token β
β grant_type=authorization_code β
β &client_id={{clientId}} β
β &code=AUTH_CODE_XYZ123 β
β &redirect_uri=https://oauth.pstmn.io/v1/callback β
β &code_verifier={{codeVerifier}} βββ Server hashes this and compares to code_challenge! β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ (Cryptographic Match: S256(code_verifier) == code_challenge)
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β 5. TOKEN RESPONSE: HTTP 200 OK β
β { "access_token": "eyJ...", "refresh_token": "r_994..", "token_type": "Bearer" } β
β - Cached into active Environment variables for subsequent wire calls β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
POSTMAN DESKTOP UI CONFIGURATION:
Location: Collection / Request -> Tab [Authorization]
Type: OAuth 2.0
Add authorization data to: Request Headers
CONFIGURATION ATTRIBUTE MATRIX:
βββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β FIELD β TARGET VALUE / EXPRESSION β
βββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Grant Type β Authorization Code (With PKCE) β
β Callback URL β https://oauth.pstmn.io/v1/callback β
β Authorize using browser β [Checked] (Enables system browser / external SSO login) β
β Auth URL β {{authServerUrl}}/oauth/authorize β
β Access Token URL β {{authServerUrl}}/oauth/token β
β Client ID β {{oauthClientId}} (e.g. portal-spa-client) β
β Client Secret β {{oauthClientSecret}} (Leave empty for public PKCE clients) β
β Code Challenge Method β SHA-256 β
β Code Verifier β <leave empty for auto-generated high-entropy cryptographic> β
β Scope β openid profile email students:read students:write β
β State β {{$randomUUID}} (CSRF verification token) β
βββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
WORKFLOW EXECUTION IN DESKTOP UI:
1. Click "Get New Access Token" button.
2. An embedded or system browser window prompts for login (Keycloak, Okta, Auth0, etc.).
3. Upon credential entry, the authorization server redirects back to Postman's callback.
4. Postman captures the code, submits the code_verifier, and displays the token details.
5. Click "Use Token" to bind the minted Bearer token to {{vault:accessToken}} or environment.
code_verifier and computes its URL-safe SHA-256 code_challenge inside a Pre-request script.
// ==============================================================================
// PRE-REQUEST SCRIPT: RFC 7636 PKCE Generator
// ==============================================================================
// 1. Generate High-Entropy Cryptographic Code Verifier (43 to 128 unreserved chars)
// Unreserved character set: [A-Z], [a-z], [0-9], "-", ".", "_", "~"
function generateCodeVerifier(length = 64) {
const charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";
const randomWords = CryptoJS.lib.WordArray.random(length);
let verifier = "";
for (let i = 0; i < length; i++) {
const byte = (randomWords.words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
verifier += charset[byte % charset.length];
}
return verifier;
}
const codeVerifier = generateCodeVerifier(64);
// 2. Compute Code Challenge: BASE64URL(SHA256(code_verifier))
const sha256Digest = CryptoJS.SHA256(codeVerifier);
// Base64URL encoding replaces '+' with '-', '/' with '_', and strips padding '='
const codeChallenge = sha256Digest.toString(CryptoJS.enc.Base64)
.replace(/\+/g, "-")
.replace(/\//g, "_")
.replace(/=+$/, "");
// 3. Generate Anti-CSRF Cryptographic State Nonce
const stateNonce = "STATE-" + CryptoJS.lib.WordArray.random(16).toString(CryptoJS.enc.Hex);
// 4. Store parameters in Environment variables for downstream verification
pm.environment.set("pkceCodeVerifier", codeVerifier);
pm.environment.set("pkceCodeChallenge", codeChallenge);
pm.environment.set("expectedOAuthState", stateNonce);
console.log(`[+] Generated Code Verifier (len: ${codeVerifier.length}): ${codeVerifier.slice(0, 20)}...`);
console.log(`[+] Computed Code Challenge (S256): ${codeChallenge}`);
console.log(`[+] Anti-CSRF State Nonce : ${stateNonce}`);
// ==============================================================================
// PRE-REQUEST SCRIPT: Headless Authorization Code Exchange Automation
// ==============================================================================
const authBase = pm.environment.get("authServerUrl") || "https://auth.nikita-infotech.com";
const tokenEndpoint = `${authBase}/oauth/token`;
const redirectUri = "https://oauth.pstmn.io/v1/callback";
const clientId = pm.environment.get("oauthClientId") || "qa-headless-runner";
// Retrieve generated PKCE verifier and challenge from Example 2
const codeVerifier = pm.environment.get("pkceCodeVerifier");
const codeChallenge = pm.environment.get("pkceCodeChallenge");
const stateNonce = pm.environment.get("expectedOAuthState");
// STEP 1: Programmatically call authorization endpoint with test user session cookie
// In headless CI, pass user session credentials to emulate immediate consent redirect
const authorizeOptions = {
url: `${authBase}/oauth/authorize?response_type=code&client_id=${clientId}&redirect_uri=${encodeURIComponent(redirectUri)}&scope=students:read%20students:write&state=${stateNonce}&code_challenge=${codeChallenge}&code_challenge_method=S256`,
method: "GET",
header: {
// Pre-authenticated session cookie established in test environment
"Cookie": pm.environment.get("testUserSessionCookie") || "session_id=MOCK-ADMIN-SESSION-88219"
}
};
console.log("[*] Dispatching headless authorization consent probe...");
pm.sendRequest(authorizeOptions, function (authErr, authRes) {
if (authErr) {
throw new Error("Headless authorization request failed: " + authErr);
}
// Step 2: Capture authorization code from 302 Found redirect or Location header
let authCode = null;
let returnedState = null;
// Look for Location header or query params
const locationHeader = authRes.headers.get("Location") || authRes.headers.get("location");
if (locationHeader) {
const codeMatch = locationHeader.match(/[?&]code=([^&]+)/);
const stateMatch = locationHeader.match(/[?&]state=([^&]+)/);
authCode = codeMatch ? codeMatch[1] : null;
returnedState = stateMatch ? stateMatch[1] : null;
}
if (!authCode) {
console.error("[-] Server response payload:", authRes.text());
throw new Error("Failed to capture authorization code from consent redirect!");
}
// CSRF Assertion: Verify returned state matches sent nonce
if (returnedState !== stateNonce) {
throw new Error(`[CSRF BREACH] State mismatch! Sent: ${stateNonce}, Received: ${returnedState}`);
}
console.log(`[β] Captured Authorization Code: ${authCode.slice(0, 10)}... (State verified)`);
// STEP 3: Exchange Authorization Code + code_verifier for Access Token
const exchangePayload = {
url: tokenEndpoint,
method: "POST",
header: { "Content-Type": "application/x-www-form-urlencoded" },
body: {
mode: "urlencoded",
urlencoded: [
{ key: "grant_type", value: "authorization_code" },
{ key: "client_id", value: clientId },
{ key: "code", value: authCode },
{ key: "redirect_uri", value: redirectUri },
{ key: "code_verifier", value: codeVerifier } // Crucial PKCE Verifier!
]
}
};
pm.sendRequest(exchangePayload, function (tokenErr, tokenRes) {
if (tokenErr || tokenRes.code !== 200) {
console.error("[-] Token redemption failed:", tokenErr || tokenRes.text());
throw new Error(`Token endpoint rejected authorization code with HTTP ${tokenRes ? tokenRes.code : 'ERR'}`);
}
const tokenData = tokenRes.json();
pm.environment.set("activeBearerToken", tokenData.access_token);
pm.environment.set("activeRefreshToken", tokenData.refresh_token);
pm.environment.set("tokenExpiryEpoch", Date.now() + (tokenData.expires_in * 1000));
// Inject minted token into the active wire request
pm.request.headers.upsert({
key: "Authorization",
value: "Bearer " + tokenData.access_token
});
console.log(`[+] Successfully exchanged PKCE code for Access Token! Valid: ${tokenData.expires_in}s`);
});
});
state parameter, verifying that the client halts execution before sending authorization codes to the token endpoint.
// ==============================================================================
// TESTS TAB: Security State Nonce Validation Guard
// ==============================================================================
pm.test("[SECURITY CSRF] Authorization callback state matches expected client nonce", function () {
const expectedState = pm.environment.get("expectedOAuthState");
const receivedState = pm.variables.get("callbackReceivedState");
pm.expect(expectedState, "expectedOAuthState variable was not initialized!").to.be.a("string").and.not.empty;
pm.expect(receivedState, "callbackReceivedState was missing from redirect!").to.be.a("string").and.not.empty;
// Strict equality check prevents Login CSRF attacks
pm.expect(
receivedState,
`SECURITY ALERT: State parameter mismatch! Sent: '${expectedState}', Received: '${receivedState}'`
).to.eql(expectedState);
console.log("[β] Anti-CSRF cryptographic handshake verified: State tokens match exactly.");
});
// Negative test case assertion
if (pm.variables.get("simulateCsrfAttack") === "true") {
pm.test("[CSRF REJECTION] Client terminates flow when state parameter is spoofed", function () {
const spoofedState = "ATTACKER-FORGED-STATE-NONCE";
const realState = pm.environment.get("expectedOAuthState");
pm.expect(spoofedState).to.not.eql(realState);
});
}
code_verifier to the token endpoint to confirm that the authorization server rejects the exchange with HTTP 400 Bad Request and invalid_grant.
// ==============================================================================
// STEP: POST /oauth/token (Submitting Malformed / Tampered code_verifier)
// Request Body payload sent:
// {
// "grant_type": "authorization_code",
// "client_id": "{{oauthClientId}}",
// "code": "{{validAuthCode}}",
// "redirect_uri": "{{redirectUri}}",
// "code_verifier": "TAMPERED-INVALID-VERIFIER-STRING-THAT-DOES-NOT-HASH-TO-CHALLENGE"
// }
// ==============================================================================
pm.test("[PKCE SECURITY] Authorization server rejects mismatched code_verifier (HTTP 400)", function () {
// 1. Assert standard RFC 6749 / RFC 7636 error response
pm.response.to.have.status(400);
const errorPayload = pm.response.json();
// 2. Assert standard OAuth error keywords
pm.expect(errorPayload).to.have.property("error");
pm.expect(errorPayload.error).to.be.oneOf(["invalid_grant", "invalid_request"]);
// 3. Confirm human-readable description explains PKCE failure
pm.expect(errorPayload).to.have.property("error_description");
pm.expect(errorPayload.error_description).to.match(/PKCE verification failed|code_verifier invalid/i);
console.log(`[β] Security Gate Confirmed: Server blocked token redemption. Detail: ${errorPayload.error_description}`);
});
refresh_token for a new token pair and updating environment variables without requiring a complete re-authorization cycle.
// ==============================================================================
// PRE-REQUEST SCRIPT: Sliding Refresh Token Rotation Engine
// ==============================================================================
const currentToken = pm.environment.get("activeBearerToken");
const refreshToken = pm.environment.get("activeRefreshToken");
const tokenExpiry = parseInt(pm.environment.get("tokenExpiryEpoch")) || 0;
const nowEpoch = Date.now();
// Check if token has expired or is within 45s of expiration
const isExpired = !currentToken || nowEpoch > (tokenExpiry - 45000);
if (isExpired && refreshToken) {
console.log("[*] Access token expired. Executing sliding refresh token exchange...");
const refreshPayload = {
url: pm.environment.get("authServerUrl") + "/oauth/token",
method: "POST",
header: { "Content-Type": "application/x-www-form-urlencoded" },
body: {
mode: "urlencoded",
urlencoded: [
{ key: "grant_type", value: "refresh_token" },
{ key: "refresh_token", value: refreshToken },
{ key: "client_id", value: pm.environment.get("oauthClientId") }
]
}
};
pm.sendRequest(refreshPayload, function (err, res) {
if (err || res.code !== 200) {
console.error("[-] Refresh token rejected or expired:", err || res.text());
pm.environment.unset("activeBearerToken");
pm.environment.unset("activeRefreshToken");
throw new Error("Refresh token failed! Re-authorization required.");
}
const data = res.json();
// Cache new Access Token
pm.environment.set("activeBearerToken", data.access_token);
pm.environment.set("tokenExpiryEpoch", Date.now() + (data.expires_in * 1000));
// Slide the Refresh Token if server issued a new one (Refresh Token Rotation)
if (data.refresh_token) {
pm.environment.set("activeRefreshToken", data.refresh_token);
console.log("[+] Sliding refresh token rotated to new key.");
}
// Bind updated token to outbound request
pm.request.headers.upsert({
key: "Authorization",
value: "Bearer " + data.access_token
});
console.log(`[β] Access token silently renewed! Validity: ${data.expires_in}s`);
});
} else if (currentToken) {
// Current token is still valid
pm.request.headers.upsert({
key: "Authorization",
value: "Bearer " + currentToken
});
}
GET /oauth/authorize and POST /oauth/token that simulate authorization codes and PKCE validation.
MOCK ENDPOINT 1: GET {{mockBaseUrl}}/oauth/authorize
--------------------------------------------------------------------------------
Expected Query Params: response_type=code, client_id, redirect_uri, code_challenge
Mock Response Header:
Location: https://oauth.pstmn.io/v1/callback?code=MOCK-AUTH-CODE-88219&state={{$query.state}}
Mock Response Status: 302 Found
Mock Response Body: (Empty)
MOCK ENDPOINT 2: POST {{mockBaseUrl}}/oauth/token
--------------------------------------------------------------------------------
Mock Request Condition:
Header: Content-Type: application/x-www-form-urlencoded
Body contains: grant_type=authorization_code && code=MOCK-AUTH-CODE-88219
Mock Response Status: 200 OK
Mock Response Headers:
Content-Type: application/json
Cache-Control: no-store
Pragma: no-cache
Mock Response Body:
{
"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c3JfOTk0MTIiLCJzY29wZXMiOlsic3R1ZGVudHM6cmVhZCJdLCJleHAiOjE3OTM1Mjg0MDB9.mockSignatureHash2026",
"token_type": "Bearer",
"expires_in": 3600,
"refresh_token": "mock_refresh_token_99412_alpha",
"scope": "students:read students:write"
}
POST /oauth/revoke) per RFC 7009 and unsets all environment variables.
// ==============================================================================
// FINAL REQUEST IN SUITE: POST /oauth/revoke - TESTS TAB
// ------------------------------------------------------------------------------
// Request Body:
// token={{activeBearerToken}}&token_type_hint=access_token&client_id={{oauthClientId}}
// ==============================================================================
pm.test("[TEARDOWN RFC 7009] Access token revoked successfully on authorization server", function () {
// RFC 7009 specifies that revocation endpoints return HTTP 200 OK
pm.response.to.have.status(200);
// List of dynamic OAuth parameters to clean from memory
const oauthKeysToPurge = [
"activeBearerToken",
"activeRefreshToken",
"pkceCodeVerifier",
"pkceCodeChallenge",
"expectedOAuthState",
"tokenExpiryEpoch"
];
// Purge variables from Environment scope
oauthKeysToPurge.forEach(function (variableKey) {
if (pm.environment.has(variableKey)) {
pm.environment.unset(variableKey);
}
});
console.log(`[β] Suite Teardown: Token revoked on server; ${oauthKeysToPurge.length} keys purged from active environment.`);
});
OAUTH 2.0 AUTHORIZATION CODE & PKCE SPECIFICATION MATRIX:
βββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββ¬βββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββ
β PARAMETER / MECHANISM β VALUE / SYNTAX β RFC SPECIFICATIONβ PRIMARY OPERATIONAL PURPOSE β
βββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββΌββββββββββββββββββββββββββββββββββ€
β response_type β "code" β RFC 6749 Β§4.1.1 β Requests authorization code β
β grant_type β "authorization_code" β RFC 6749 Β§4.1.3 β Redeems code at token endpoint β
β grant_type (Refresh) β "refresh_token" β RFC 6749 Β§6 β Obtains fresh token via refresh β
β code_verifier β 43-128 random unreserved str β RFC 7636 Β§4.1 β Client cryptographically secret β
β code_challenge β BASE64URL(SHA256(verifier)) β RFC 7636 Β§4.2 β Public challenge sent to /auth β
β code_challenge_method β "S256" β RFC 7636 Β§4.3 β Mandates SHA-256 (not "plain") β
β state β Cryptographic random nonce β RFC 6749 Β§10.12 β Anti-CSRF verification token β
β redirect_uri β https://oauth.pstmn.io/... β RFC 6749 Β§3.1.2 β Explicit callback destination β
β Token Revocation β POST /oauth/revoke β RFC 7009 β Invalidates tokens on teardown β
β Browser Redirection β "Authorize using browser" β Postman UI β Supports external SSO / MFA β
βββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββ΄βββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββ€
β TOP 5 PKCE & AUTH CODE BEST PRACTICES: β
β 1. Always use code_challenge_method=S256: Never use "plain"; SHA-256 is required for security. β
β 2. Validate state tokens on callback: Assert receivedState === expectedState to prevent CSRF attacks. β
β 3. Use 60s expiration buffers: Renew tokens proactively before they expire during long runs. β
β 4. Keep tokens in Current Values: Never persist minted tokens to cloud-synced Initial Values. β
β 5. Revoke tokens on teardown: Call /oauth/revoke in final collection steps to clean up active sessions. β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ