API KEYS & BEARER JWT AUTH: TOKEN INGESTION, DECODING & CHAINING

Architect enterprise token-based security automation in REST Assured: Header and query-based API Key injection, OAuth2 Client Credentials grant flows, Bearer JWT injection via .auth().oauth2() and explicit headers, programmatic JWT Base64URL claims decoding, token expiration validation, and multi-tenant key rotation.

πŸ”‘ Token-Based Security, Asymmetric Signatures & Multi-Service Chaining

Modern distributed microservices and cloud API gateways rely primarily on stateless token-based authorization rather than legacy session cookies. API Keys act as identifier tokens transmitted via custom headers (such as x-api-key) or URL query strings, identifying the calling project or tenant and enforcing rate-limiting quotas. For authenticated user and service-to-service communication, JSON Web Tokens (JWT) under RFC 7519 serve as standard, cryptographically signed Bearer tokens transmitted within the Authorization: Bearer <token> transport header. In automated test suites, mastering this architecture requires two capabilities: orchestrating OAuth2 token acquisition chaining (requesting a token via client credentials and injecting it into subsequent calls) and performing in-memory token decoding and inspection (parsing claims such as exp, sub, iss, and roles without external libraries) to assert security compliance and token validity before invoking downstream APIs.

1. Token Wire Architecture & JWT RFC 7519 Segment Anatomy
The architectural structure of an RFC 7519 JSON Web Token, demonstrating how header, payload claims, and cryptographic signatures are encoded into three Base64URL dot-delimited segments and transmitted across HTTP transport layers.
JWT Token Segment Topography & Wire Transmission
RFC 7519 JSON WEB TOKEN (JWT) WIRE ENCODING & TRANSMISSION ANATOMY:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJuaWtpdGEtc2hhcm1hIiwicm9sZXMiOlsiUk9MRV9BRE1JTiJdfQ.w6uV9qY7V-w0Q6a7w
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜.β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜.β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                   β”‚                                           β”‚                                       β”‚
           SEGMENT 1: HEADER                           SEGMENT 2: PAYLOAD                      SEGMENT 3: SIGNATURE
         Base64URL(JOSE Header)                      Base64URL(JWT Claims Set)               HMAC-SHA256 / RSA-256
      {"alg":"HS256","typ":"JWT"}                 {"sub":"nikita-sharma", ...}            Cryptographic tamper seal

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ TOKEN INGESTION & TRANSPORT INJECTION SURFACE:                                                               β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ AUTHENTICATION TYPE β”‚ INJECTION METHOD             β”‚ WIRE LOCATION              β”‚ PRIMARY OPERATIONAL ROLE   β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ API Key (Header)    β”‚ .header("x-api-key", key)    β”‚ Custom Transport Header    β”‚ Gateway quota & routing    β”‚
β”‚ API Key (Query)     β”‚ .queryParam("api_key", key)  β”‚ URL Query Parameter        β”‚ Public client ingestion    β”‚
β”‚ Bearer Token        β”‚ .auth().oauth2(token)        β”‚ Authorization: Bearer <tok>β”‚ RFC 6750 Token submission  β”‚
β”‚ Direct Bearer Headerβ”‚ .header("Authorization", ..) β”‚ Authorization: Bearer <tok>β”‚ Direct explicit injection  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
Architectural Standard: Under RFC 6750, Bearer tokens must always be prefixed with the word "Bearer " followed by a single space. Using REST Assured's .auth().oauth2(token) or setting .header("Authorization", "Bearer " + token) produces the identical HTTP transport header.
Real-Time Example 1: Header-Based API Key Authentication via header()
Injecting an API key via custom headers (such as x-api-key or X-Tenant-Key). Demonstrates verifying authentication, quota headers, and successful entity access.
Java (Header-Based API Key Injection)
package com.nikita.restassured.auth;

import org.testng.annotations.Test;

import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;

public class HeaderApiKeyTest {

    private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";
    private static final String TEST_API_KEY = "live_sec_key_88219_pune_masterclass";

    @Test(description = "Authenticate against API Gateway using header-based API key")
    public void testHeaderBasedApiKey() {
        given()
            .baseUri(BASE_URI)
            // Inject API Key into target gateway header:
            .header("x-api-key", TEST_API_KEY)
            .header("X-Tenant-Id", "MH-PUNE-WEST")
            .log().ifValidationFails()
        .when()
            .get("/courses/catalog")
        .then()
            .log().ifValidationFails()
            .statusCode(200)
            .header("X-RateLimit-Remaining", notNullValue())
            .body("status", equalTo("SUCCESS"))
            .body("data", notNullValue());

        System.out.println("[βœ”] Header-based API key authenticated successfully; gateway rate limits verified.");
    }
}
Execution Output: GET /v1/courses/catalog -> HTTP 200 OK [94ms] Inbound Headers: X-RateLimit-Limit: 1000 X-RateLimit-Remaining: 984 X-RateLimit-Reset: 1793614800 Status: 200 OK | Authenticated via x-api-key header.
Real-Time Example 2: Query Parameter API Key Authentication via queryParam()
Passing API keys in URL query strings (e.g. ?api_key=...). Demonstrates testing services where third-party webhooks, public telemetry, or mapping APIs ingest authentication via query criteria.
Java (Query Parameter API Key Injection)
package com.nikita.restassured.auth;

import org.testng.annotations.Test;

import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;

public class QueryApiKeyTest {

    private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";
    private static final String PUBLIC_TELEMETRY_KEY = "pk_live_telemetry_99482";

    @Test(description = "Authenticate public telemetry endpoint via query string API key")
    public void testQueryStringApiKey() {
        given()
            .baseUri(BASE_URI)
            // Injects ?api_key=pk_live_telemetry_99482 into target request URI
            .queryParam("api_key", PUBLIC_TELEMETRY_KEY)
            .queryParam("format", "json")
            .log().uri()
        .when()
            .get("/telemetry/system-ping")
        .then()
            .statusCode(200)
            .body("ping", equalTo("PONG"))
            .body("authorizedTier", equalTo("PUBLIC_TELEMETRY"));

        System.out.println("[βœ”] Query-string API key authenticated cleanly.");
    }
}
Wire Output: Request URI: https://staging-api.nikita-infotech.com/v1/telemetry/system-ping?api_key=pk_live_telemetry_99482&format=json HTTP/1.1 200 OK [42ms] Response: {"ping":"PONG","authorizedTier":"PUBLIC_TELEMETRY"} PASSED: testQueryStringApiKey
Real-Time Example 3: Bearer Token Injection via .auth().oauth2() vs. Explicit Header
Comparing REST Assured's native .auth().oauth2(token) method against explicit .header("Authorization", "Bearer " + token) injection. Demonstrates that both patterns yield identical HTTP wire packets.
Java (Bearer Token Injection: oauth2() vs. Explicit Header)
package com.nikita.restassured.auth;

import org.testng.annotations.Test;

import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;

public class BearerTokenInjectionTest {

    private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";
    private static final String STATIC_JWT = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJuaWtpdGEiLCJyb2xlcyI6WyJBRE1JTiJdfQ.SignatureValue";

    // =========================================================================
    // PATTERN A: NATIVE REST ASSURED auth().oauth2(token)
    // =========================================================================
    @Test(description = "Inject Bearer token using native .auth().oauth2(token) DSL")
    public void testNativeOAuth2BearerInjection() {
        given()
            .baseUri(BASE_URI)
            // auth().oauth2() automatically prefixes the string with 'Bearer ' on the wire:
            .auth().oauth2(STATIC_JWT)
            .pathParam("studentId", "STU-88219")
        .when()
            .get("/students/{studentId}/grades")
        .then()
            .statusCode(200)
            .body("status", equalTo("SUCCESS"));

        System.out.println("[βœ”] Native .auth().oauth2(token) verified.");
    }

    // =========================================================================
    // PATTERN B: EXPLICIT HEADER INJECTION (PREFERRED IN ENTERPRISE FRAMEWORKS)
    // =========================================================================
    @Test(description = "Inject Bearer token using explicit Authorization header")
    public void testExplicitAuthorizationHeaderInjection() {
        given()
            .baseUri(BASE_URI)
            // Explicit header construction (allows easy parameterization and custom schemes)
            .header("Authorization", "Bearer " + STATIC_JWT)
            .pathParam("studentId", "STU-88219")
        .when()
            .get("/students/{studentId}/grades")
        .then()
            .statusCode(200)
            .body("status", equalTo("SUCCESS"));

        System.out.println("[βœ”] Explicit Authorization: Bearer header verified.");
    }
}
Transport Inspection Telemetry: Pattern A Wire Header: Authorization: Bearer eyJhbGciOiJIUzI1Ni... Pattern B Wire Header: Authorization: Bearer eyJhbGciOiJIUzI1Ni... Both approaches produce identical HTTP transport envelopes on the wire.
Real-Time Example 4: End-to-End OAuth2 Token Acquisition & Dynamic Request Chaining
Orchestrating end-to-end OAuth2 token acquisition. Dispatches a POST to the authorization server with client_credentials, extracts the minted access token from the JSON response, and chains that token into downstream API requests.
Java (OAuth2 Token Acquisition & Downstream Chaining Pipeline)
package com.nikita.restassured.auth;

import io.restassured.http.ContentType;
import org.testng.Assert;
import org.testng.annotations.Test;

import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;

public class OAuth2TokenChainingTest {

    private static final String AUTH_SERVER = "https://auth.nikita-infotech.com";
    private static final String RESOURCE_SERVER = "https://staging-api.nikita-infotech.com/v1";

    @Test(description = "Acquire Bearer token via OAuth2 client_credentials and chain into protected API")
    public void testOAuth2TokenAcquisitionAndChaining() {
        // =====================================================================
        // STEP 1: REQUEST OAUTH2 ACCESS TOKEN (Client Credentials Grant)
        // =====================================================================
        String mintedAccessToken = given()
            .baseUri(AUTH_SERVER)
            .contentType(ContentType.URLENC.withCharset("UTF-8"))
            .formParam("grant_type", "client_credentials")
            .formParam("client_id", "sdet-automation-worker")
            .formParam("client_secret", "Secret#Enterprise2026Key")
            .formParam("scope", "students.read students.write")
            .log().ifValidationFails()
        .when()
            .post("/oauth/v2/token")
        .then()
            .log().ifValidationFails()
            .statusCode(200)
            .contentType(ContentType.JSON)
            .body("token_type", equalToIgnoringCase("Bearer"))
            .body("access_token", notNullValue())
            .body("expires_in", greaterThan(0))
            .extract()
            .path("access_token");

        System.out.println("[Step 1] Minted Access Token: " + mintedAccessToken.substring(0, 20) + "...");
        Assert.assertNotNull(mintedAccessToken, "OAuth access token acquisition failed!");

        // =====================================================================
        // STEP 2: DISPATCH CALL TO RESOURCE SERVER USING EXTRACTED TOKEN
        // =====================================================================
        given()
            .baseUri(RESOURCE_SERVER)
            // Forward dynamic token in Authorization header
            .header("Authorization", "Bearer " + mintedAccessToken)
            .pathParam("studentId", "STU-88219")
        .when()
            .get("/students/{studentId}/transcripts")
        .then()
            .statusCode(200)
            .body("status", equalTo("SUCCESS"))
            .body("data.studentId", equalTo("STU-88219"));

        System.out.println("[Step 2] Resource server authorized dynamic Bearer token successfully.");
    }
}
Chaining Telemetry: [Step 1] POST https://auth.nikita-infotech.com/oauth/v2/token -> HTTP 200 OK [184ms] Body: {"token_type":"Bearer","access_token":"eyJhbGciOiJIUz...","expires_in":3600} [Step 1] Minted Access Token: eyJhbGciOiJIUzI1NiIsIn... [Step 2] GET https://staging-api.nikita-infotech.com/v1/students/STU-88219/transcripts -> HTTP 200 OK [112ms] Dynamic token successfully extracted from auth server and passed to resource gateway.
Real-Time Example 5: Programmatic In-Memory JWT Decoding & Claims Validation
Inspecting JWT internal payload claims without third-party JWT libraries. Splits the token at dot delimiters, decodes the Base64URL payload bytes, parses the JSON claims via JsonPath, and asserts identity attributes and roles.
Java (Programmatic JWT Claims Decoder & JsonPath Extraction)
package com.nikita.restassured.auth;

import io.restassured.path.json.JsonPath;
import org.testng.Assert;
import org.testng.annotations.Test;

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.List;

public class JwtDecodingAndClaimsTest {

    // Sample valid JWT token generated for testing
    private static final String SAMPLE_JWT = 
            "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9." +
            "eyJzdWIiOiJuaWtpdGEuc2hhcm1hQG5pa2l0YS1pbmZvdGVjaC5jb20iLCJuYW1lIjoiTmlraXRhIFNoYXJtYSIsImlzcyI6ImF1dGgubmlraXRhLWluZm90ZWNoLmNvbSIsImV4cCI6MTgwMDAwMDAwMCwicm9sZXMiOlsiUk9MRV9BRE1JTiIsIlJPTEVfU0RFVCJdfQ." +
            "w6uV9qY7V-w0Q6a7w_FAKE_SIGNATURE_HASH";

    @Test(description = "Decode JWT payload claims in-memory and assert identity attributes via JsonPath")
    public void testDecodeJwtClaimsWithoutExternalLibraries() {
        // Step 1: Split JWT into its 3 RFC 7519 segments: Header [0], Payload [1], Signature [2]
        String[] jwtSegments = SAMPLE_JWT.split("\\.");
        Assert.assertEquals(jwtSegments.length, 3, "Invalid JWT format! Must contain exactly 3 dot-delimited parts.");

        // Step 2: Decode Base64URL encoded payload (Segment 1)
        byte[] decodedBytes = Base64.getUrlDecoder().decode(jwtSegments[1]);
        String payloadJson = new String(decodedBytes, StandardCharsets.UTF_8);

        System.out.println("---------------- DECODED JWT PAYLOAD CLAIMS ----------------");
        System.out.println(payloadJson);
        System.out.println("------------------------------------------------------------");

        // Step 3: Ingest decoded payload string directly into REST Assured's JsonPath parser
        JsonPath jwtClaims = new JsonPath(payloadJson);

        String subject = jwtClaims.getString("sub");
        String issuer = jwtClaims.getString("iss");
        long expirationEpoch = jwtClaims.getLong("exp");
        List<String> assignedRoles = jwtClaims.getList("roles");

        // Step 4: Validate token security claims
        Assert.assertEquals(subject, "nikita.sharma@nikita-infotech.com", "Subject mismatch!");
        Assert.assertEquals(issuer, "auth.nikita-infotech.com", "Issuer mismatch!");
        Assert.assertTrue(expirationEpoch > 1700000000L, "Token expiration epoch must be in the future!");
        Assert.assertTrue(assignedRoles.contains("ROLE_ADMIN"), "Admin authority claim is missing!");

        System.out.println("[βœ”] Decoded JWT claims verified: Subject, Issuer, Expiration, and Roles.");
    }
}
Decoded JWT Output: ---------------- DECODED JWT PAYLOAD CLAIMS ---------------- {"sub":"nikita.sharma@nikita-infotech.com","name":"Nikita Sharma","iss":"auth.nikita-infotech.com","exp":1800000000,"roles":["ROLE_ADMIN","ROLE_SDET"]} ------------------------------------------------------------ Decoded Claims: β€’ sub = nikita.sharma@nikita-infotech.com β€’ iss = auth.nikita-infotech.com β€’ exp = 1800000000 (Valid future epoch) β€’ roles = [ROLE_ADMIN, ROLE_SDET] Verified internal claims without requiring external heavy dependencies.
Real-Time Example 6: Token Expiration Audit & Expired Token Rejection
Verifying token lifetime boundaries. Tests that the gateway rejects expired JWTs (where exp < current_epoch) with HTTP 401 Unauthorized and an expired_token error code.
Java (Testing Expired Token Rejection Boundaries)
package com.nikita.restassured.auth;

import org.testng.annotations.Test;

import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;

public class TokenExpirationTest {

    private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";

    // Expired JWT containing claim: "exp": 1500000000 (Past timestamp)
    private static final String EXPIRED_JWT = 
            "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9." +
            "eyJzdWIiOiJuaWtpdGEiLCJleHAiOjE1MDAwMDAwMDAsInJvbGVzIjpbIlNURVNUXyJdfQ." +
            "SignatureHashDataForTesting";

    @Test(description = "Verify API Gateway rejects expired Bearer token with 401 and token_expired error")
    public void testExpiredTokenReturns401() {
        given()
            .baseUri(BASE_URI)
            .header("Authorization", "Bearer " + EXPIRED_JWT)
            .log().ifValidationFails()
        .when()
            .get("/students/STU-88219/grades")
        .then()
            .log().ifValidationFails()
            // Gateway must reject expired token with 401 Unauthorized
            .statusCode(401)
            .header("WWW-Authenticate", containsString("error=\"invalid_token\""))
            .header("WWW-Authenticate", containsString("error_description=\"The access token expired\""))
            .body("error", equalTo("TOKEN_EXPIRED"));

        System.out.println("[βœ”] Gateway rejected expired JWT with compliant 401 and WWW-Authenticate details.");
    }
}
Expired Token Rejection Output: GET /v1/students/STU-88219/grades -> HTTP 401 Unauthorized [36ms] Header: WWW-Authenticate: Bearer error="invalid_token", error_description="The access token expired" Body: {"error":"TOKEN_EXPIRED","status":401} PASSED: testExpiredTokenReturns401
Real-Time Example 7: Centralizing Auth in RequestSpecBuilder with Dynamic Token Injection
Standardizing token-based authentication across an entire test framework. Creates a reusable RequestSpecBuilder factory that dynamically injects Bearer tokens or API keys into pre-configured specifications.
Java (TokenSpecFactory.java Reusable Security Specifications)
package com.nikita.restassured.auth;

import io.restassured.builder.RequestSpecBuilder;
import io.restassured.http.ContentType;
import io.restassured.specification.RequestSpecification;
import org.testng.annotations.Test;

import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;

public class TokenSpecFactory {

    private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";

    // Reusable factory method assembling authenticated Bearer specification
    public static RequestSpecification getBearerTokenSpec(String jwtToken) {
        return new RequestSpecBuilder()
                .setBaseUri(BASE_URI)
                .setContentType(ContentType.JSON)
                .setAccept(ContentType.JSON)
                .addHeader("Authorization", "Bearer " + jwtToken)
                .addHeader("X-Client-Platform", "REST-Assured-Masterclass")
                .build();
    }

    // Reusable factory method assembling authenticated API Key specification
    public static RequestSpecification getApiKeySpec(String apiKey) {
        return new RequestSpecBuilder()
                .setBaseUri(BASE_URI)
                .setContentType(ContentType.JSON)
                .addHeader("x-api-key", apiKey)
                .build();
    }

    // =========================================================================
    // USAGE IN TEST EXECUTION
    // =========================================================================
    @Test(description = "Verify endpoint execution using factory-assembled Bearer specification")
    public void testExecuteEndpointWithFactorySpec() {
        String testJwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJuaWtpdGEifQ.Signature";
        RequestSpecification authSpec = TokenSpecFactory.getBearerTokenSpec(testJwt);

        given()
            .spec(authSpec)
            .pathParam("studentId", "STU-88219")
        .when()
            .get("/students/{studentId}")
        .then()
            .statusCode(200)
            .body("status", equalTo("SUCCESS"));

        System.out.println("[βœ”] Executed test using factory-assembled Bearer specification.");
    }
}
Spec Factory Telemetry: Bound specification: BaseURI="https://staging-api...", Authorization="Bearer eyJ...", ContentType=JSON GET /v1/students/STU-88219 -> HTTP 200 OK [118ms] Eliminates repetitive header declarations by parameterizing tokens via factory methods.
Real-Time Example 8: Negative Security Testing: Missing Keys, Malformed Tokens & 403 Scopes
Negative test suite covering authorization edge cases: missing API keys (HTTP 401), malformed garbage Bearer tokens, and valid tokens with insufficient scope permissions (HTTP 403 Forbidden).
Java (Negative Security Testing: 401, 403 & Malformed Tokens)
package com.nikita.restassured.auth;

import org.testng.annotations.Test;

import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;

public class NegativeTokenSecurityTest {

    private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";

    @Test(description = "Verify missing API key header produces HTTP 401 Unauthorized")
    public void testMissingApiKeyProduces401() {
        given()
            .baseUri(BASE_URI)
            // Intentionally omit x-api-key header
        .when()
            .get("/courses/catalog")
        .then()
            .statusCode(401)
            .body("detail", containsString("API key is missing or invalid"));

        System.out.println("[βœ”] 401 Unauthorized asserted for missing API key.");
    }

    @Test(description = "Verify malformed garbage JWT produces HTTP 401 Unauthorized")
    public void testMalformedJwtProduces401() {
        given()
            .baseUri(BASE_URI)
            // Pass broken, non-RFC-compliant token string
            .header("Authorization", "Bearer THIS_IS_NOT_A_VALID_DOT_SEPARATED_JWT")
        .when()
            .get("/students/STU-88219")
        .then()
            .statusCode(401)
            .body("error", equalTo("INVALID_TOKEN"));

        System.out.println("[βœ”] 401 Unauthorized asserted for malformed JWT syntax.");
    }

    @Test(description = "Verify valid token with read-only scope produces 403 Forbidden on DELETE operation")
    public void testInsufficientScopeProduces403Forbidden() {
        // Token containing scope: "students.read" only
        String readOnlyToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJuaWtpdGEiLCJzY29wZSI6InN0dWRlbnRzLnJlYWQifQ.Signature";

        given()
            .baseUri(BASE_URI)
            .header("Authorization", "Bearer " + readOnlyToken)
            .pathParam("studentId", "STU-88219")
        .when()
            // Attempting mutation with read-only token
            .delete("/students/{studentId}")
        .then()
            // Authenticated successfully, but rejected on scope authorization:
            .statusCode(403)
            .body("detail", containsString("Insufficient scope: requires 'students.write'"));

        System.out.println("[βœ”] 403 Forbidden asserted for insufficient scope permissions.");
    }
}
Negative Security Telemetry: GET /v1/courses/catalog (No API Key) -> HTTP 401 Unauthorized [32ms] (PASSED) GET /v1/students/STU-88219 (Malformed JWT) -> HTTP 401 Unauthorized [24ms] (PASSED) DELETE /v1/students/STU-88219 (Read Token) -> HTTP 403 Forbidden [46ms] (PASSED) All boundary conditions and authorization gates verified.
Real-Time Example 9: API Keys & Bearer JWT Specification Reference Matrix
A comprehensive reference summary pairing authentication constructs, REST Assured DSL methods, RFC specifications, and operational best practices for API automation engineers.
API Keys & Bearer JWT Specification Reference Matrix
API KEYS & BEARER JWT AUTHENTICATION SPECIFICATION MATRIX:
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ SECURITY CONSTRUCT      β”‚ REST ASSURED DSL METHOD      β”‚ RFC STANDARD     β”‚ PRIMARY OPERATIONAL PURPOSE   β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ Header-Based API Key    β”‚ .header("x-api-key", key)    β”‚ Custom Header    β”‚ Injects API key into header   β”‚
β”‚ Query-Based API Key     β”‚ .queryParam("api_key", key)  β”‚ URL Query String β”‚ Injects API key into URL queryβ”‚
β”‚ Native OAuth2 Bearer    β”‚ .auth().oauth2(token)        β”‚ RFC 6750         β”‚ Injects Authorization: Bearer β”‚
β”‚ Explicit Bearer Header  β”‚ .header("Authorization", ..) β”‚ RFC 6750         β”‚ Direct Authorization: Bearer  β”‚
β”‚ OAuth2 Token Harvest    β”‚ formParam("grant_type", ..)  β”‚ RFC 6749         β”‚ Requests OAuth access token   β”‚
β”‚ Token Extraction        β”‚ extract().path("access_token")JsonPath          β”‚ Extracts token for chaining   β”‚
β”‚ In-Memory JWT Decoding  β”‚ Base64.getUrlDecoder()       β”‚ RFC 7519         β”‚ Decodes JWT payload claims    β”‚
β”‚ Claims Extraction       β”‚ new JsonPath(decodedPayload) β”‚ JsonPath Parser  β”‚ Interrogates exp, sub, roles  β”‚
β”‚ Reusable Token Spec     β”‚ RequestSpecBuilder           β”‚ Spec Model       β”‚ Centralizes token headers     β”‚
β”‚ Expired Token Check     β”‚ .statusCode(401)             β”‚ RFC 6750         β”‚ Validates expired token rejectβ”‚
β”‚ Scope Permission Check  β”‚ .statusCode(403)             β”‚ RFC 7231         β”‚ Validates insufficient scopes β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ TOP 5 TOKEN & API KEY TESTING BEST PRACTICES:                                                             β”‚
β”‚ 1. Chain OAuth2 tokens dynamically: Request tokens in setup steps and chain them into test suites.        β”‚
β”‚ 2. Decode JWT claims in-memory: Verify exp, sub, and roles directly using Java Base64URL and JsonPath.    β”‚
β”‚ 3. Test negative expiration boundaries: Assert that expired tokens return 401 with invalid_token tags.    β”‚
β”‚ 4. Distinguish 401 vs. 403 errors: Validate 401 for invalid tokens and 403 for insufficient scopes.       β”‚
β”‚ 5. Parameterize tokens via RequestSpecBuilder: Keep test methods clean and credential-free.               β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
Engineering Best Practice: Modern API security requires robust validation of both transport and token semantics. By automating OAuth2 token harvesting, decoding JWT claims in-memory without external dependencies, testing expired token rejection, and validating 403 scope boundaries, you build resilient, production-ready test automation for enterprise identity architectures.