π« Stateless Cryptographic Identity & Self-Contained Session Governance
In modern cloud-native systems, microservices avoid centralized database session lookups by delegating authentication to JSON Web Tokens (JWTs) transmitted via the RFC 6750 Bearer Token specification. A JWT is a cryptographically signed, URL-safe compact representation consisting of three distinct segments separated by periods: header.payload.signature. Because access tokens are intentionally short-lived (often expiring in 15 to 60 minutes), automated test suites run the risk of sudden 401 Unauthorized failures halfway through long-running execution runs. By inspecting the token payload directly inside the Postman JavaScript Sandbox, test engineers can decode claims without third-party dependencies, evaluate the remaining expiration window against current epoch time, validate subject (sub) and role-based permissions (scopes), and automatically trigger zero-touch background renewal using pm.sendRequest() before wire dispatch.
JWT COMPACT SERIALIZATION STRUCTURE:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJVU1ItODgyMTkiLCJyb2xlIjoiU0RFVCIsImV4cCI6MTc5MzUyODQwMCwiaWF0IjoxNzkzNTI0ODAwLCJpc3MiOiJhdXRoLm5pa2l0YS1pbmZvdGVjaC5jb20ifQ.k3f..._signature
βββββββββββββββββββ¬ββββββββββββββββββ ββββββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββ ββββββββββββββββββββββββ¬βββββββββββββββββββββββ
β β β
PART 1: JOSE HEADER PART 2: JWT PAYLOAD PART 3: SIGNATURE
βββββββββββββββββββββββββββββββββββ βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ βββββββββββββββββββββββββββββββββββ
β Base64URL Decoded: β β Base64URL Decoded: β β Computed Cryptographic Digest: β
β { β β { β β HMACSHA256( β
β "alg": "HS256", β β "sub": "USR-88219", β β base64Url(Header) + "." + β
β "typ": "JWT" β β "role": "SDET_AUTOMATION", β β base64Url(Payload), β
β } β β "exp": 1793528400, // Expiration Unix Epoch (sec) β β secretKey β
β β β "iat": 1793524800, // Issued-at Unix Epoch (sec) β β ) β
β β’ Defines signing algorithm β β "iss": "auth.nikita-infotech.com", β β β
β β’ Verified by backend gateway β β "scopes": ["students:read", "students:write"] β β β’ Detects payload tampering β
βββββββββββββββββββββββββββββββββββ β } β β β’ Guarantees authenticity β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ βββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β HTTP WIRE TRANSMISSION (RFC 6750): β
β GET /api/v1/students/catalog HTTP/1.1 β
β Host: api.nikita-infotech.com β
β Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJVU1ItODgyMTki... β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
-, _) back to standard Base64 and decodes UTF-8 strings cleanly.
// ==============================================================================
// POSTMAN SANDBOX UTILITY: Native Base64URL JWT Decoder Function
// Place in Collection-Level Pre-request Scripts or Tests Tab
// ==============================================================================
function parseJwt(tokenString) {
if (!tokenString || typeof tokenString !== "string") {
console.warn("[-] Invalid or empty token string supplied to parseJwt()");
return null;
}
try {
// Split compact serialization into [header, payload, signature]
const segments = tokenString.split(".");
if (segments.length !== 3) {
console.error("[-] Supplied string does not have 3 tripartite JWT segments.");
return null;
}
// Segment 1: Header | Segment 2: Payload Claims
const base64UrlHeader = segments[0];
const base64UrlPayload = segments[1];
// Helper: Convert Base64URL to standard Base64 and decode URI components
function decodeSegment(b64Url) {
let base64 = b64Url.replace(/-/g, "+").replace(/_/g, "/");
// Pad base64 string with '=' if length is not a multiple of 4
while (base64.length % 4) {
base64 += "=";
}
// Decode base64 to percent-encoded string, then decode URI to handle multi-byte UTF-8
const rawDecoded = atob(base64);
const utf8Decoded = Array.prototype.map.call(rawDecoded, function (c) {
return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
}).join("");
return JSON.parse(decodeURIComponent(utf8Decoded));
}
return {
header: decodeSegment(base64UrlHeader),
payload: decodeSegment(base64UrlPayload)
};
} catch (parseError) {
console.error("[-] Failed to decode and parse JWT:", parseError.message);
return null;
}
}
// Example Execution Inspection
const sampleJwt = pm.environment.get("activeBearerToken");
if (sampleJwt) {
const decoded = parseJwt(sampleJwt);
console.log("[*] Decoded JWT Header :", JSON.stringify(decoded.header));
console.log("[*] Decoded JWT Payload :", JSON.stringify(decoded.payload));
}
sub), issuer (iss), issue time (iat), and ensuring the expiration window is within allowed policy bounds.
// ==============================================================================
// STEP: POST /api/v1/auth/token - TESTS TAB (Claim Contract Verification)
// ==============================================================================
pm.test("[JWT SPECIFICATION] Token response satisfies standard claim contract", function () {
pm.response.to.have.status(200);
const res = pm.response.json();
pm.expect(res).to.have.property("access_token");
const decoded = parseJwt(res.access_token);
pm.expect(decoded, "Failed to decode access_token into valid JWT segments").to.not.be.null;
const payload = decoded.payload;
const currentEpochSeconds = Math.floor(Date.now() / 1000);
// 1. Mandatory Standard Claims Presence
pm.expect(payload).to.have.property("sub");
pm.expect(payload).to.have.property("iss");
pm.expect(payload).to.have.property("exp");
pm.expect(payload).to.have.property("iat");
// 2. Identity & Issuer Validations
pm.expect(payload.sub).to.match(/^USR-[0-9]{5,}$/);
pm.expect(payload.iss).to.eql("auth.nikita-infotech.com");
// 3. Temporal Validity: Issued in the past/present, not in the future
pm.expect(payload.iat).to.be.at.most(currentEpochSeconds + 5);
// 4. Lifespan Window Audit (Must be valid for exactly 3600s / 1 Hour Β± 30s)
const tokenLifespanSeconds = payload.exp - payload.iat;
console.log(`[*] Calculated Token Lifespan: ${tokenLifespanSeconds} seconds`);
pm.expect(tokenLifespanSeconds).to.be.within(3570, 3630);
// 5. Active Validity: exp must be strictly greater than current time
pm.expect(payload.exp).to.be.above(currentEpochSeconds);
});
exp claim against current time using a 60-second safety buffer, triggering renewal early to guarantee the token remains valid during transmission.
// ==============================================================================
// PRE-REQUEST SCRIPT: Proactive Token Expiration & Safety Buffer Gating
// ==============================================================================
const currentToken = pm.environment.get("activeBearerToken");
const refreshBufferSeconds = 60; // 60s buffer accounts for network latency and clock drift
let isTokenUsable = false;
if (currentToken) {
const decoded = parseJwt(currentToken);
if (decoded && decoded.payload && decoded.payload.exp) {
const expEpoch = decoded.payload.exp;
const nowEpoch = Math.floor(Date.now() / 1000);
const remainingSeconds = expEpoch - nowEpoch;
console.log(`[*] Active JWT Status: Remaining life = ${remainingSeconds}s (Safety Threshold = ${refreshBufferSeconds}s)`);
// Check if token has more than 60 seconds of valid life remaining
if (remainingSeconds > refreshBufferSeconds) {
isTokenUsable = true;
console.log("[β] Token is fresh and healthy. Skipping re-authentication.");
} else {
console.warn(`[!] Token expired or entering safety buffer (${remainingSeconds}s remaining). Refresh required!`);
}
}
}
if (isTokenUsable) {
// Inject active token into outbound wire header
pm.request.headers.upsert({
key: "Authorization",
value: "Bearer " + currentToken
});
} else {
// Proceed to trigger silent token acquisition (Example 4)
pm.variables.set("needsTokenRenewal", "true");
}
pm.sendRequest(), caches the fresh JWT, and injects it into the primary request.
// ==============================================================================
// COLLECTION PRE-REQUEST SCRIPT: Zero-Touch Self-Healing JWT Pipeline
// ==============================================================================
function ensureValidBearerToken() {
const activeJwt = pm.environment.get("activeBearerToken");
const now = Math.floor(Date.now() / 1000);
// Check if current token exists and has > 60 seconds remaining
if (activeJwt) {
const decoded = parseJwt(activeJwt);
if (decoded && decoded.payload.exp && (decoded.payload.exp - now) > 60) {
pm.request.headers.upsert({ key: "Authorization", value: "Bearer " + activeJwt });
return; // Exit: Existing token is valid
}
}
console.log("[*] Acquiring fresh Bearer JWT via pre-flight handshake...");
const authEndpoint = pm.environment.get("authUrl") || "https://auth.nikita-infotech.com/oauth/token";
const clientId = pm.environment.get("clientId") || "qa-automation-client";
const clientSecret = pm.environment.get("clientSecret") || "Secret#2026Key";
// Asynchronous token acquisition request configuration
const tokenRequestOptions = {
url: authEndpoint,
method: "POST",
header: {
"Content-Type": "application/x-www-form-urlencoded"
},
body: {
mode: "urlencoded",
urlencoded: [
{ key: "grant_type", value: "client_credentials" },
{ key: "client_id", value: clientId },
{ key: "client_secret", value: clientSecret },
{ key: "scope", value: "students:read students:write billing:read" }
]
}
};
// Execute out-of-band call before main request hits the wire
pm.sendRequest(tokenRequestOptions, function (err, res) {
if (err || res.code !== 200) {
console.error("[-] Fatal error acquiring fresh token:", err || res.text());
throw new Error("Pre-flight JWT token renewal failed!");
}
const freshToken = res.json().access_token;
// Persist token in Environment scope (Current Value local RAM only)
pm.environment.set("activeBearerToken", freshToken);
// Inject refreshed Bearer header onto the primary outbound request
pm.request.headers.upsert({
key: "Authorization",
value: "Bearer " + freshToken
});
console.log("[+] Fresh Bearer JWT minted and injected onto wire request.");
});
}
// Execute self-healing guard
ensureValidBearerToken();
roles, scopes, tenantId) before invoking sensitive endpoints.
// ==============================================================================
// TESTS TAB: Security Claims & Scope Authorization Audit
// ==============================================================================
pm.test("[RBAC CLAIMS] Active token carries authorized administrative permissions", function () {
const token = pm.environment.get("activeBearerToken");
pm.expect(token, "activeBearerToken variable is not set!").to.not.be.undefined;
const decoded = parseJwt(token);
const claims = decoded.payload;
// 1. Verify User Role Assignment
pm.expect(claims).to.have.property("role");
pm.expect(claims.role).to.be.oneOf(["ADMIN", "LEAD_INSTRUCTOR"]);
// 2. Verify Tenant Partition Binding
const expectedTenant = pm.environment.get("tenantId") || "MH-PUNE-01";
pm.expect(claims).to.have.property("tenantId");
pm.expect(claims.tenantId).to.eql(expectedTenant);
// 3. Verify Permission Scopes Array
pm.expect(claims).to.have.property("scopes");
pm.expect(claims.scopes).to.be.an("array");
// Assert required permission scopes are present
pm.expect(claims.scopes).to.include.members([
"students:write",
"billing:admin",
"grades:finalize"
]);
console.log(`[β] Verified Scopes for ${claims.sub}: [${claims.scopes.join(", ")}]`);
});
STUDENT to ADMIN) to confirm that the backend gateway detects signature mismatches and returns 401 Unauthorized.
// ==============================================================================
// 1. PRE-REQUEST SCRIPT: Simulating Privilege Escalation Tampering
// ==============================================================================
const validJwt = pm.environment.get("activeBearerToken");
if (validJwt) {
const parts = validJwt.split(".");
// parts[0] = header, parts[1] = payload, parts[2] = signature
// Decode original payload
const decodedPayload = JSON.parse(atob(parts[1].replace(/-/g, "+").replace(/_/g, "/")));
// MALICIOUS MUTATION: Escalate standard user to superuser
decodedPayload.role = "SUPERUSER_ADMIN";
decodedPayload.scopes = ["*"];
// Re-encode modified payload to Base64URL
const tamperedPayloadB64 = btoa(JSON.stringify(decodedPayload))
.replace(/\+/g, "-")
.replace(/\//g, "_")
.replace(/=+$/, "");
// Reconstruct token with ORIGINAL signature (now mismatched!)
const tamperedJwt = `${parts[0]}.${tamperedPayloadB64}.${parts[2]}`;
// Inject tampered token into request header
pm.request.headers.upsert({
key: "Authorization",
value: "Bearer " + tamperedJwt
});
console.warn("[!] Tampered JWT injected with escalated permissions and stale signature.");
}
// ==============================================================================
// 2. TESTS TAB: Assert Gateway Rejection
// ==============================================================================
pm.test("[SECURITY GATE] Gateway detects signature mismatch and returns HTTP 401", function () {
pm.response.to.have.status(401);
pm.response.to.have.header("WWW-Authenticate");
const res = pm.response.json();
pm.expect(res.message).to.match(/invalid signature|signature mismatch|tampered/i);
});
nbf (Not Before) claim properly when tokens are used before their allowed activation window.
// ==============================================================================
// 1. PRE-REQUEST SCRIPT: Expired Token Simulation
// ==============================================================================
if (pm.variables.get("simulateExpiredToken") === "true") {
// Construct dummy expired token (exp set to 1 hour in the past)
const expiredHeader = btoa(JSON.stringify({ alg: "HS256", typ: "JWT" }));
const expiredPayload = btoa(JSON.stringify({
sub: "USR-EXPIRED-TEST",
exp: Math.floor(Date.now() / 1000) - 3600, // 1 Hour Ago
iat: Math.floor(Date.now() / 1000) - 7200
}));
const dummySignature = "stale_signature_segment";
const expiredToken = `${expiredHeader}.${expiredPayload}.${dummySignature}`
.replace(/\+/g, "-").replace(/\//g, "_");
pm.request.headers.upsert({
key: "Authorization",
value: "Bearer " + expiredToken
});
console.warn("[!] Injected expired JWT token into outbound request.");
}
// ==============================================================================
// 2. TESTS TAB: Assert Expired Token Rejection
// ==============================================================================
if (pm.variables.get("simulateExpiredToken") === "true") {
pm.test("[EXPIRED REJECTION] Server returns HTTP 401 with token_expired code", function () {
pm.response.to.have.status(401);
const authHeader = pm.response.headers.get("WWW-Authenticate") || "";
const body = pm.response.json();
// Verify either header or JSON body explicitly flags expiration
const indicatesExpiry = authHeader.includes("error=\"invalid_token\"") ||
(body.errorCode && body.errorCode.includes("EXPIRED"));
pm.expect(indicatesExpiry, "Response did not indicate token expiration").to.be.true;
});
}
// ==============================================================================
// FINAL REQUEST IN SUITE: POST /api/v1/auth/logout - TESTS TAB
// ==============================================================================
pm.test("[TEARDOWN & GC] Session revoked and token memory purged", function () {
pm.response.to.have.status(200);
// List of dynamic token variables to clear
const tokenKeysToPurge = [
"activeBearerToken",
"jwtRefreshToken",
"activeClaimsSubject",
"needsTokenRenewal"
];
// Purge tokens from Environment Current Values (Local RAM)
tokenKeysToPurge.forEach(function (keyName) {
if (pm.environment.has(keyName)) {
pm.environment.unset(keyName);
}
});
console.log(`[β] Garbage Collection Complete: ${tokenKeysToPurge.length} token variables purged from memory.`);
});
JWT CLAIMS & BEARER WORKFLOW SPECIFICATION MATRIX:
βββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββ¬βββββββββββββββββββ¬ββββββββββββββββββββββββββββββββ
β CLAIM / PRIMITIVE β PAYLOAD EXAMPLE β RFC STANDARD β PRIMARY OPERATIONAL PURPOSE β
βββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββΌββββββββββββββββββββββββββββββββ€
β sub (Subject) β "sub": "USR-88219" β RFC 7519 Β§4.1.2 β Unique identity principal key β
β exp (Expiration) β "exp": 1793528400 β RFC 7519 Β§4.1.4 β Unix epoch second expiration β
β iat (Issued At) β "iat": 1793524800 β RFC 7519 Β§4.1.6 β Unix epoch issue timestamp β
β iss (Issuer) β "iss": "auth.nikita...com" β RFC 7519 Β§4.1.1 β Trusted authority domain β
β nbf (Not Before) β "nbf": 1793524800 β RFC 7519 Β§4.1.3 β Token not valid before epoch β
β scopes / roles β "scopes": ["read", "write"] β OAuth 2.0 / RBAC β Permitted authorization actionsβ
β Header Segment β {"alg": "HS256", "typ":"JWT"}β RFC 7515 (JWS) β Declares signing algorithm β
β atob() Decode Helper β atob(seg.replace(/-/g, '+')) β Sandbox Native β Decodes Base64URL claims β
β 60-Second Buffer β (exp - now) > 60 seconds β Test Pattern β Prevents in-flight 401 errors β
β pm.sendRequest() β Out-of-band renewal request β Sandbox API β Silently mints fresh tokens β
βββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββ΄βββββββββββββββββββ΄ββββββββββββββββββββββββββββββββ€
β TOP 5 JWT WORKFLOW BEST PRACTICES: β
β 1. Proactively renew with safety buffers: Refresh tokens 60s before exp to avoid mid-transit failures. β
β 2. Decode claims without external libraries: Use native atob() to inspect exp, sub, and scopes. β
β 3. Never store secrets in Current Values: Keep tokens in Current Values; never sync to Postman Cloud. β
β 4. Test signature tampering: Alter payloads to confirm gateways catch signature mismatches (401). β
β 5. Purge tokens on teardown: Unset activeBearerToken on suite completion for clean subsequent runs. β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ