πͺ Transport Metadata Governance, Session Tracking & Wire Context
While entity payloads encapsulate business data, HTTP Headers and Cookies govern transport negotiation, identity validation, caching strategies, and stateful session boundaries across distributed microservices. In RESTful communication, headers transmit critical contextual metadataβsuch as content negotiation (Accept, Content-Type), authorization tokens (Bearer JWT), correlation tracing identifiers (X-Request-ID), and cache revalidation tags (ETag, If-None-Match). Concurrently, cookies facilitate stateful session affinity (JSESSIONID, session_token) across load-balanced cloud clusters and security enforcement via browser flags (HttpOnly, Secure, SameSite). REST Assured provides a strongly typed API via header(), headers(), cookie(), and cookies(), enabling test engineers to inject complex multi-value headers, capture session state, and evaluate transport-level assertions cleanly within the Given-When-Then BDD pipeline.
HTTP TRANSPORT METADATA EXCHANGE PIPELINE:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β CLIENT OUTBOUND DISPATCH (REST Assured Given Phase) β
β βββ Headers: .header("Accept", "application/json").header("X-Tenant-ID", "MH-PUNE-01") β
β βββ Multi-Value: .header(new Header("Accept-Encoding", "gzip"), new Header("...", "deflate"))β
β βββ Cookies: .cookie("JSESSIONID", "sess_994821a0bc").cookie("auth_env", "staging") β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ (Over TCP / TLS 1.3 Transport Stream)
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β API GATEWAY & SERVICE MESH PROCESSING (Ingress NGINX / Kong / Spring Cloud Gateway) β
β βββ Evaluates client credentials and extracts tenant routing keys from custom headers β
β βββ Validates session state and correlates incoming transaction via X-Correlation-ID β
β βββ Generates response context: cache directives, ETags, security headers, Set-Cookie headersβ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ (Over Wire Response Stream)
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β SERVER INBOUND RESPONSE (REST Assured Then & Extract Phase) β
β βββ Response Headers: .header("Content-Type", containsString("json")) β
β β β’ Security Headers: Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options β
β β β’ Cache Control: Cache-Control: max-age=3600, must-revalidate, ETag: W/"88219-hash" β
β βββ Set-Cookie Directives: .cookie("session_token", notNullValue()) β
β β’ Detailed Attributes: Value, Domain, Path, Max-Age, ExpiryDate, isHttpOnly, isSecured β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Map<String, Object>.
package com.nikita.restassured.metadata;
import io.restassured.http.ContentType;
import org.testng.annotations.Test;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
public class HeaderInjectionTest {
private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";
@Test(description = "Inject single and chained headers in Given phase")
public void testChainedHeaderInjection() {
String correlationId = UUID.randomUUID().toString();
given()
.baseUri(BASE_URI)
// Single header injections
.header("X-Correlation-ID", correlationId)
.header("X-Tenant-Key", "MAHARASHTRA_PUNE_01")
.header("X-Client-Version", "2.4.0")
.accept(ContentType.JSON)
.log().headers()
.when()
.get("/students/STU-88219")
.then()
.statusCode(200)
.header("X-Correlation-ID", equalTo(correlationId))
.body("status", equalTo("SUCCESS"));
System.out.println("[β] Chained headers injected and correlation ID echoed successfully.");
}
@Test(description = "Inject bulk request headers using a Java Map")
public void testBulkHeadersViaMap() {
Map<String, Object> customHeaderMap = new HashMap<>();
customHeaderMap.put("X-Client-Platform", "Java-Automation-Runner");
customHeaderMap.put("X-Environment-Tier", "Staging");
customHeaderMap.put("X-Request-Source", "REST-Assured-Masterclass");
customHeaderMap.put("Accept-Language", "en-IN,en;q=0.9");
given()
.baseUri(BASE_URI)
// Injecting an entire Map of headers in a single call:
.headers(customHeaderMap)
.accept(ContentType.JSON)
.when()
.get("/students")
.then()
.statusCode(200);
System.out.println("[β] Bulk headers from Map injected cleanly into outbound request.");
}
}
Accept, Accept-Encoding, or tracking headers). Utilizes REST Assured's Header and Headers collection models.
package com.nikita.restassured.metadata;
import io.restassured.http.Header;
import io.restassured.http.Headers;
import io.restassured.response.Response;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.util.List;
import static io.restassured.RestAssured.given;
public class MultiValueHeaderTest {
private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";
@Test(description = "Inject multi-value headers where the same header key appears multiple times")
public void testMultiValueHeaderInjection() {
// Instantiate individual Header objects with identical keys but distinct values
Header encodingGzip = new Header("Accept-Encoding", "gzip");
Header encodingDeflate = new Header("Accept-Encoding", "deflate");
Header encodingBr = new Header("Accept-Encoding", "br");
// Bundle into a strongly-typed Headers collection object
Headers multiEncodingHeaders = new Headers(encodingGzip, encodingDeflate, encodingBr);
Response response = given()
.baseUri(BASE_URI)
.headers(multiEncodingHeaders)
.log().headers()
.when()
.get("/students")
.then()
.statusCode(200)
.extract()
.response();
// Extract and inspect multi-value headers from inbound response
Headers returnedHeaders = response.getHeaders();
List<String> varyValues = returnedHeaders.getValues("Vary");
System.out.println("[*] Received 'Vary' response values: " + varyValues);
Assert.assertNotNull(varyValues, "Vary header must be present on cached catalog endpoint!");
}
}
HSTS, CSP, X-Content-Type-Options) and conditional cache revalidation using ETag and If-None-Match (HTTP 304 Not Modified).
package com.nikita.restassured.metadata;
import io.restassured.response.Response;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
public class SecurityAndCacheHeadersTest {
private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";
@Test(description = "Verify OWASP enterprise security headers are enforced on gateway responses")
public void testOwaspSecurityHeaders() {
given()
.baseUri(BASE_URI)
.when()
.get("/students/STU-88219")
.then()
.statusCode(200)
// 1. HTTP Strict Transport Security (HSTS)
.header("Strict-Transport-Security", containsString("max-age=31536000"))
// 2. MIME Sniffing Protection
.header("X-Content-Type-Options", equalTo("nosniff"))
// 3. Clickjacking Protection
.header("X-Frame-Options", equalTo("DENY"))
// 4. Content Security Policy (CSP)
.header("Content-Security-Policy", notNullValue())
// 5. Anti-Cross-Site Scripting Filter
.header("X-XSS-Protection", containsString("1; mode=block"));
System.out.println("[β] All OWASP security transport headers validated successfully.");
}
@Test(description = "Verify ETag caching contract and 304 Not Modified handshake")
public void testEtagConditionalCacheValidation() {
// Step 1: Initial GET request to retrieve ETag token
Response initialResponse = given()
.baseUri(BASE_URI)
.when()
.get("/students/STU-88219")
.then()
.statusCode(200)
.header("ETag", notNullValue())
.extract().response();
String eTagValue = initialResponse.getHeader("ETag");
System.out.println("[*] Captured ETag identifier: " + eTagValue);
// Step 2: Issue conditional GET using If-None-Match header
given()
.baseUri(BASE_URI)
.header("If-None-Match", eTagValue) // Pass captured ETag back to server
.when()
.get("/students/STU-88219")
.then()
// Server recognizes state is unchanged; returns 304 Not Modified with empty body:
.statusCode(304)
.header("ETag", equalTo(eTagValue));
System.out.println("[β] ETag conditional validation returned HTTP 304 Not Modified as expected.");
}
}
io.restassured.http.Cookie instances with attributes like Domain, Path, Expiry, and Security flags.
package com.nikita.restassured.metadata;
import io.restassured.http.Cookie;
import io.restassured.http.Cookies;
import org.testng.annotations.Test;
import java.util.HashMap;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
public class CookieInjectionTest {
private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";
@Test(description = "Inject single and chained basic key-value cookies")
public void testBasicCookieInjection() {
given()
.baseUri(BASE_URI)
.cookie("session_tier", "enterprise_gold")
.cookie("ui_theme", "dark_mode")
.cookie("preferred_locale", "en-IN")
.log().cookies()
.when()
.get("/portal/preferences")
.then()
.statusCode(200)
.body("theme", equalTo("dark_mode"));
System.out.println("[β] Chained key-value cookies dispatched and verified.");
}
@Test(description = "Inject detailed cookies using the strongly-typed Cookie.Builder")
public void testDetailedCookieBuilderInjection() {
// Construct comprehensive Cookie with security attributes
Cookie secureSessionCookie = new Cookie.Builder("SESSION_TRACKER", "token_sec_4f8a10c9bf12")
.setDomain("nikita-infotech.com")
.setPath("/v1")
.setSecured(true)
.setHttpOnly(true)
.setComment("Automated integration test session cookie")
.setMaxAge(3600)
.build();
Cookie featureFlagCookie = new Cookie.Builder("BETA_MIGRATION_V2", "ENABLED")
.setPath("/")
.build();
Cookies customCookieJar = new Cookies(secureSessionCookie, featureFlagCookie);
given()
.baseUri(BASE_URI)
// Bind complete Cookies container to outbound request
.cookies(customCookieJar)
.when()
.get("/portal/session/verify")
.then()
.statusCode(200)
.body("sessionValid", equalTo(true));
System.out.println("[β] Strongly-typed Cookie.Builder attributes injected into wire session.");
}
@Test(description = "Inject bulk cookies using a standard Java Map")
public void testBulkCookiesViaMap() {
Map<String, String> cookieMap = new HashMap<>();
cookieMap.put("tracking_consent", "ACCEPTED");
cookieMap.put("affiliate_id", "AFF-PUNE-88219");
given()
.baseUri(BASE_URI)
.cookies(cookieMap)
.when()
.get("/portal/context")
.then()
.statusCode(200);
System.out.println("[β] Bulk cookies injected cleanly via Map.");
}
}
Set-Cookie values from inbound responses. Demonstrates retrieving raw cookie string values, extracting detailed Cookie objects, and asserting critical security attributes like isHttpOnly() and isSecured().
package com.nikita.restassured.metadata;
import io.restassured.http.Cookie;
import io.restassured.response.Response;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.notNullValue;
public class CookieExtractionTest {
private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";
@Test(description = "Extract inbound cookie values and validate detailed security flags")
public void testExtractAndValidateResponseCookies() {
Response authResponse = given()
.baseUri(BASE_URI)
.contentType("application/json")
.body("{\"username\":\"sdet-lead\",\"password\":\"Pass#Pune2026\"}")
.when()
.post("/auth/login")
.then()
.statusCode(200)
// Assert presence of session cookie in response envelope
.cookie("JSESSIONID", notNullValue())
.extract().response();
// =====================================================================
// TECHNIQUE A: EXTRACT SINGLE COOKIE VALUE (STRING)
// =====================================================================
String rawSessionId = authResponse.getCookie("JSESSIONID");
System.out.println("[+] Extracted raw JSESSIONID value: " + rawSessionId);
Assert.assertNotNull(rawSessionId, "JSESSIONID cookie must not be null!");
// =====================================================================
// TECHNIQUE B: EXTRACT ALL COOKIES AS A MAP
// =====================================================================
Map<String, String> allCookiesMap = authResponse.getCookies();
System.out.println("[+] Total cookies extracted: " + allCookiesMap.size());
allCookiesMap.forEach((k, v) -> System.out.println(" β’ " + k + " = " + v));
// =====================================================================
// TECHNIQUE C: EXTRACT DETAILED COOKIE OBJECT TO AUDIT SECURITY FLAGS
// =====================================================================
Cookie detailedSessionCookie = authResponse.getDetailedCookie("JSESSIONID");
System.out.println("---------------- COOKIE SECURITY AUDIT ----------------");
System.out.println(" Cookie Name : " + detailedSessionCookie.getName());
System.out.println(" Cookie Value : " + detailedSessionCookie.getValue());
System.out.println(" Domain : " + detailedSessionCookie.getDomain());
System.out.println(" Path : " + detailedSessionCookie.getPath());
System.out.println(" Expiry Date : " + detailedSessionCookie.getExpiryDate());
System.out.println(" Max Age : " + detailedSessionCookie.getMaxAge());
System.out.println(" isHttpOnly? : " + detailedSessionCookie.isHttpOnly());
System.out.println(" isSecured? : " + detailedSessionCookie.isSecured());
System.out.println("-------------------------------------------------------");
// Enforce strict security compliance assertions
Assert.assertTrue(detailedSessionCookie.isHttpOnly(),
"SECURITY DEFECT: JSESSIONID must have HttpOnly flag set to prevent XSS theft!");
Assert.assertTrue(detailedSessionCookie.isSecured(),
"SECURITY DEFECT: JSESSIONID must have Secure flag set for HTTPS transmission!");
Assert.assertEquals(detailedSessionCookie.getPath(), "/",
"Cookie path must be root bound!");
}
}
package com.nikita.restassured.metadata;
import io.restassured.http.ContentType;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
public class SessionChainingTest {
private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";
private String activeSessionId;
@Test(priority = 1, description = "Step 1: Authenticate and extract session affinity cookie")
public void step1_loginAndAcquireSession() {
activeSessionId = given()
.baseUri(BASE_URI)
.contentType(ContentType.JSON)
.body("{\"username\":\"student.qa\",\"password\":\"SecurePass#2026\"}")
.when()
.post("/auth/session-login")
.then()
.statusCode(200)
.extract()
.cookie("SESSION_AFFINITY_ID");
System.out.println("[Step 1] Acquired Session Cookie: " + activeSessionId);
}
@Test(priority = 2, dependsOnMethods = "step1_loginAndAcquireSession",
description = "Step 2: Dispatch authenticated request using extracted session cookie")
public void step2_accessProtectedResourceWithSession() {
given()
.baseUri(BASE_URI)
// Forward captured cookie to maintain stateful affinity:
.cookie("SESSION_AFFINITY_ID", activeSessionId)
.when()
.get("/students/dashboard/profile")
.then()
.statusCode(200)
.body("status", equalTo("AUTHENTICATED"))
.body("userRole", equalTo("STUDENT_QA"));
System.out.println("[Step 2] Authenticated dashboard accessed successfully using session cookie.");
}
@Test(priority = 3, dependsOnMethods = "step2_accessProtectedResourceWithSession",
description = "Step 3: Invalidate session on logout and assert cookie expiry")
public void step3_logoutAndTerminateSession() {
given()
.baseUri(BASE_URI)
.cookie("SESSION_AFFINITY_ID", activeSessionId)
.when()
.post("/auth/session-logout")
.then()
.statusCode(200)
// Verify server issues a Set-Cookie clearing the session (Max-Age=0 or blank value)
.cookie("SESSION_AFFINITY_ID", equalTo(""));
System.out.println("[Step 3] Session terminated cleanly. Cookie invalidated on server.");
}
}
RequestSpecBuilder to configure universal headers, tenant context, and authentication cookies in an immutable specification applied across test suites.
package com.nikita.restassured.metadata;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.http.ContentType;
import io.restassured.http.Cookie;
import io.restassured.http.Header;
import io.restassured.specification.RequestSpecification;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
public class SpecBuilderMetadataTest {
private RequestSpecification commonApiSpec;
@BeforeClass
public void setupMetadataSpecification() {
// Build reusable specification template encapsulating common headers and cookies
commonApiSpec = new RequestSpecBuilder()
.setBaseUri("https://staging-api.nikita-infotech.com")
.setBasePath("/v1")
.setContentType(ContentType.JSON)
.setAccept(ContentType.JSON)
// Add default enterprise headers
.addHeader("X-Tenant-Id", "CAMPUS_PUNE_WEST")
.addHeader("X-Client-Platform", "Automation-Worker")
.addHeader(new Header("X-Environment-Mode", "Automated-Regression"))
// Add default session and locale cookies
.addCookie(new Cookie.Builder("app_locale", "en-US").build())
.addCookie("routing_pool", "alpha_canary")
.build();
System.out.println("[*] Common API RequestSpecification template initialized.");
}
@Test(description = "Verify endpoint inheriting headers and cookies from RequestSpecification")
public void testEndpointWithSharedSpec() {
given()
// Bind complete template: headers, cookies, baseUri applied in one call!
.spec(commonApiSpec)
.queryParam("limit", 5)
.when()
.get("/students")
.then()
.statusCode(200)
.body("status", equalTo("SUCCESS"));
System.out.println("[β] Request executed using reusable headers & cookies template.");
}
}
400 Bad Request, malformed bearer tokens producing 401 Unauthorized, and cookie domain mismatches. Uses RequestLoggingFilter and ResponseLoggingFilter to capture wire diagnostics.
package com.nikita.restassured.metadata;
import io.restassured.filter.log.RequestLoggingFilter;
import io.restassured.filter.log.ResponseLoggingFilter;
import io.restassured.http.ContentType;
import org.testng.annotations.Test;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
public class MetadataDebuggingTest {
private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";
@Test(description = "Verify missing mandatory header triggers 400 Bad Request with descriptive error")
public void testMissingMandatoryHeaderThrows400() {
given()
.baseUri(BASE_URI)
.contentType(ContentType.JSON)
// Intentionally omitting mandatory "X-Tenant-Id" header!
.log().ifValidationFails()
.when()
.get("/students")
.then()
.log().ifValidationFails()
.statusCode(400)
.body("detail", containsString("Missing mandatory header: 'X-Tenant-Id'"));
System.out.println("[β] Gateway rejected request lacking mandatory header with 400 Bad Request.");
}
@Test(description = "Capture complete wire metadata to in-memory stream for CI diagnostic dumps")
public void testCaptureWireMetadataToStream() {
ByteArrayOutputStream logStream = new ByteArrayOutputStream();
PrintStream customPrintStream = new PrintStream(logStream);
given()
.baseUri(BASE_URI)
.header("X-Tenant-Id", "CAMPUS_PUNE_WEST")
.filter(RequestLoggingFilter.logRequestTo(customPrintStream))
.filter(ResponseLoggingFilter.logResponseTo(customPrintStream))
.when()
.get("/health")
.then()
.statusCode(200);
String capturedTraffic = logStream.toString();
System.out.println("---------------- CAPTURED WIRE TELEMETRY ----------------");
System.out.println(capturedTraffic.substring(0, Math.min(capturedTraffic.length(), 400)) + "...");
System.out.println("---------------------------------------------------------");
}
}
REST ASSURED HEADERS & COOKIES SPECIFICATION MATRIX:
βββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββ¬βββββββββββββββββββ¬ββββββββββββββββββββββββββββββββ
β TRANSPORT ENTITY β DSL METHOD SIGNATURE β ARGUMENT TYPES β PRIMARY OPERATIONAL PURPOSE β
βββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββΌββββββββββββββββββββββββββββββββ€
β Single Header Injection β .header(name, value) β String, Object β Injects single header on wire β
β Bulk Headers (Map) β .headers(Map<String, ?>) β Map of Key-Valuesβ Injects multiple custom headerβ
β Multi-Value Headers β .headers(Headers headers) β Headers / Header β Repeated header keys (Accept) β
β Inbound Header Assert β .then().header(name, matcher)β String, Matcher β Asserts response header value β
β Extract Single Header β .response().getHeader(name) β String (Name) β Returns string header value β
β Extract All Headers β .response().getHeaders() β N/A (Method) β Returns Headers collection objβ
β Single Cookie Injection β .cookie(name, value) β String, Object β Injects basic key-value cookieβ
β Bulk Cookies (Map) β .cookies(Map<String, ?>) β Map of Key-Valuesβ Injects multiple cookies β
β Detailed Cookie Builder β .cookie(Cookie cookie) β Cookie Instance β Domain, Path, HttpOnly, Secureβ
β Extract Single Cookie β .response().getCookie(name) β String (Name) β Returns raw cookie value (Str)β
β Detailed Cookie Extract β .getDetailedCookie(name) β String (Name) β Returns Cookie obj with flags β
β Extract All Cookies β .response().getCookies() β N/A (Method) β Returns Map<String, String> β
β Shared Metadata Spec β RequestSpecBuilder β Spec Model β Centralizes headers & cookies β
βββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββ΄βββββββββββββββββββ΄ββββββββββββββββββββββββββββββββ€
β TOP 5 HEADERS & COOKIES BEST PRACTICES: β
β 1. Verify HttpOnly and Secure flags: Ensure session cookies cannot be accessed by scripts or HTTP. β
β 2. Test ETag caching with 304 Not Modified: Validate that unchanged resources conserve bandwidth. β
β 3. Forward correlation IDs: Attach X-Correlation-ID headers to trace requests across microservice logs β
β 4. Centralize headers via RequestSpecBuilder: Eliminate duplicate header declarations across tests. β
β 5. Audit OWASP security headers: Enforce HSTS, X-Content-Type-Options, and CSP in automated suites. β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ