πͺ Wire Interception, Middleware Pipelines & Aspect-Oriented Testing
In enterprise API automation suites, cross-cutting concernsβsuch as distributed correlation tracing, PII payload redaction, automated OAuth2 token refresh cycles, and HTML report loggingβmust not clutter business-level test scripts. Attempting to manage authentication retries or audit telemetry inside each individual test method violates separation of concerns and leads to high code duplication. REST Assured Filters provide a powerful interception and middleware mechanism based on the Chain of Responsibility pattern. By implementing the io.restassured.filter.Filter or OrderedFilter interfaces, test architects intercept outbound FilterableRequestSpecification objects prior to socket dispatch and capture inbound Response instances before assertion evaluation. This enables automated token refreshment on 401 Unauthorized responses, latency benchmarking, and seamless attachment of request/response bodies to Allure Reports.
FILTER CHAIN OF RESPONSIBILITY EXECUTION TOPOGRAPHY:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β TEST PIPELINE TRIGGER: given().filter(filterA).filter(filterB).when().get("/students") β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ (Outbound Request Interception)
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β FILTER A: Correlation & Timing Interceptor (OrderedFilter - Priority: 1) β
β βββ Injects X-Correlation-ID header into FilterableRequestSpecification β
β βββ Captures System.currentTimeMillis() β
β βββ Invokes ctx.next(requestSpec, responseSpec) βββΊ Passes downstream β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β FILTER B: Security Token & PII Masking Interceptor (OrderedFilter - Priority: 2) β
β βββ Inspects request body; masks sensitive passwords or credit card numbers β
β βββ Attaches Bearer JWT authentication header β
β βββ Invokes ctx.next(requestSpec, responseSpec) βββΊ Passes downstream β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β WIRE SOCKET DISPATCH: Ingress HTTP Connection (Apache HttpClient) β
β Dispatches HTTP GET /v1/students βββΊ Receives HTTP Response Packet β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ (Inbound Response Interception Bubble-Up)
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β FILTER B (Return Phase): Evaluates Response Status β
β βββ If status == 401 Unauthorized: Acquires new OAuth token & re-executes request β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β FILTER A (Return Phase): Evaluates Response Performance β
β βββ Calculates total elapsed round-trip time: (System.currentTimeMillis() - start) β
β βββ Attaches wire transcripts to Allure / Extent Reports β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β TERMINAL THEN PHASE: .then().statusCode(200).body(...) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Filter interface. Demonstrates intercepting outbound request URIs, headers, and inbound response status codes to build a clean console audit logger.
package com.nikita.restassured.filters;
import io.restassured.filter.Filter;
import io.restassured.filter.FilterContext;
import io.restassured.response.Response;
import io.restassured.specification.FilterableRequestSpecification;
import io.restassured.specification.FilterableResponseSpecification;
public class ConsoleAuditFilter implements Filter {
@Override
public Response filter(FilterableRequestSpecification requestSpec,
FilterableResponseSpecification responseSpec,
FilterContext ctx) {
// -------------------------------------------------------------
// PRE-EXECUTION: Intercept and inspect outbound request
// -------------------------------------------------------------
System.out.println("\nβββββββββββββββββββββ [OUTBOUND REQUEST] βββββββββββββββββββββ");
System.out.println("HTTP Method : " + requestSpec.getMethod());
System.out.println("Target URI : " + requestSpec.getURI());
System.out.println("Headers : " + requestSpec.getHeaders());
if (requestSpec.getBody() != null) {
System.out.println("Body : " + requestSpec.getBody().toString());
}
System.out.println("ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ");
// Delegate execution down the filter chain to dispatch HTTP wire call
Response response = ctx.next(requestSpec, responseSpec);
// -------------------------------------------------------------
// POST-EXECUTION: Intercept and inspect inbound response
// -------------------------------------------------------------
System.out.println("\nβββββββββββββββββββββ [INBOUND RESPONSE] βββββββββββββββββββββ");
System.out.println("Status Code : " + response.getStatusCode() + " " + response.getStatusLine());
System.out.println("Latency : " + response.getTime() + " ms");
System.out.println("Content-Type: " + response.getContentType());
System.out.println("ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n");
// Return original response back to REST Assured validation pipeline
return response;
}
}
filter(), centralized across a RequestSpecBuilder, or registered globally via RestAssured.filters().
package com.nikita.restassured.filters;
import io.restassured.RestAssured;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.specification.RequestSpecification;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
public class FilterScopeRegistrationTest {
private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";
// =========================================================================
// SCOPE 1: AD-HOC PER-REQUEST FILTER ATTACHMENT
// =========================================================================
@Test(description = "Apply custom filter ad-hoc to a single specific test execution")
public void testAdHocFilterAttachment() {
given()
.baseUri(BASE_URI)
// Bind filter directly into Given statement
.filter(new ConsoleAuditFilter())
.pathParam("studentId", "STU-88219")
.when()
.get("/students/{studentId}")
.then()
.statusCode(200)
.body("status", equalTo("SUCCESS"));
System.out.println("[β] Executed request with ad-hoc filter.");
}
// =========================================================================
// SCOPE 2: CENTRALIZED ATTACHMENT VIA REQUESTSPECBUILDER
// =========================================================================
@Test(description = "Attach filter universally across a shared RequestSpecification")
public void testSpecBuilderFilterAttachment() {
RequestSpecification specWithFilter = new RequestSpecBuilder()
.setBaseUri(BASE_URI)
.addFilter(new ConsoleAuditFilter()) // Attached to reusable spec
.build();
given()
.spec(specWithFilter)
.when()
.get("/students")
.then()
.statusCode(200);
System.out.println("[β] Executed request with RequestSpecification filter.");
}
// =========================================================================
// SCOPE 3: GLOBAL REGISTRATION ACROSS THE ENTIRE JVM TEST RUNNER
// =========================================================================
public static void registerGlobalFilter() {
// Registers filter for all subsequent given() calls throughout the entire project
RestAssured.filters(new ConsoleAuditFilter());
System.out.println("[*] Registered ConsoleAuditFilter globally into RestAssured.filters().");
}
}
FilterableRequestSpecification dynamically to inject a unique UUID X-Correlation-ID on every outgoing call.
package com.nikita.restassured.filters;
import io.restassured.filter.Filter;
import io.restassured.filter.FilterContext;
import io.restassured.response.Response;
import io.restassured.specification.FilterableRequestSpecification;
import io.restassured.specification.FilterableResponseSpecification;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.util.UUID;
import static io.restassured.RestAssured.given;
public class CorrelationTracingFilter implements Filter {
public static final String CORRELATION_HEADER = "X-Correlation-ID";
@Override
public Response filter(FilterableRequestSpecification requestSpec,
FilterableResponseSpecification responseSpec,
FilterContext ctx) {
// Check if correlation ID already exists; if not, generate a fresh unique UUID
if (!requestSpec.getHeaders().hasHeaderWithName(CORRELATION_HEADER)) {
String generatedCorrelationId = "TRACE-" + UUID.randomUUID().toString();
// Mutate outbound request headers prior to wire dispatch:
requestSpec.header(CORRELATION_HEADER, generatedCorrelationId);
System.out.println("[*] Injected correlation header: " + generatedCorrelationId);
}
// Proceed with downstream filter chain
return ctx.next(requestSpec, responseSpec);
}
}
// ==============================================================================
// VERIFICATION TEST METHOD
// ==============================================================================
class TracingFilterTest {
@Test(description = "Verify CorrelationTracingFilter automatically injects X-Correlation-ID")
public void testAutomaticTracingInjection() {
given()
.baseUri("https://staging-api.nikita-infotech.com/v1")
.filter(new CorrelationTracingFilter())
.when()
.get("/health")
.then()
.statusCode(200);
System.out.println("[β] Outbound request contained automatically injected correlation header.");
}
}
401 Unauthorized responses, invokes a token generation endpoint to acquire fresh credentials, updates the session token, and re-executes the failed call automatically.
package com.nikita.restassured.filters;
import io.restassured.RestAssured;
import io.restassured.filter.Filter;
import io.restassured.filter.FilterContext;
import io.restassured.response.Response;
import io.restassured.specification.FilterableRequestSpecification;
import io.restassured.specification.FilterableResponseSpecification;
public class TokenRenewalFilter implements Filter {
// Volatile shared token across concurrent test executions
private static volatile String activeBearerToken = "EXPIRED_STALE_TOKEN_999";
@Override
public Response filter(FilterableRequestSpecification requestSpec,
FilterableResponseSpecification responseSpec,
FilterContext ctx) {
// Step 1: Attach current active token to outbound request
requestSpec.header("Authorization", "Bearer " + activeBearerToken);
// Step 2: Dispatch request downstream
Response response = ctx.next(requestSpec, responseSpec);
// Step 3: Intercept 401 Unauthorized status indicating token expiration
if (response.getStatusCode() == 401) {
System.out.println("[!] Intercepted HTTP 401 Unauthorized. Refreshing expired OAuth token...");
// Synchronize token acquisition to avoid thundering herd across threads
synchronized (TokenRenewalFilter.class) {
activeBearerToken = acquireNewBearerToken();
System.out.println("[+] Successfully acquired fresh token: " + activeBearerToken.substring(0, 15) + "...");
}
// Step 4: Mutate request specification with the new valid token
requestSpec.removeHeader("Authorization");
requestSpec.header("Authorization", "Bearer " + activeBearerToken);
// Step 5: Re-execute the exact same request using FilterContext
System.out.println("[*] Re-executing original request with updated Bearer token...");
response = ctx.next(requestSpec, responseSpec);
}
return response;
}
private String acquireNewBearerToken() {
// Out-of-band call to authentication endpoint
return RestAssured.given()
.baseUri("https://auth.nikita-infotech.com")
.contentType("application/x-www-form-urlencoded")
.formParam("grant_type", "client_credentials")
.formParam("client_id", "sdet-automation-worker")
.formParam("client_secret", "Secret#Enterprise2026")
.post("/oauth/v2/token")
.then()
.statusCode(200)
.extract()
.path("access_token");
}
}
package com.nikita.restassured.filters;
import io.restassured.filter.Filter;
import io.restassured.filter.FilterContext;
import io.restassured.response.Response;
import io.restassured.specification.FilterableRequestSpecification;
import io.restassured.specification.FilterableResponseSpecification;
public class PerformanceBenchmarkingFilter implements Filter {
private final long warningThresholdMs;
public PerformanceBenchmarkingFilter(long warningThresholdMs) {
this.warningThresholdMs = warningThresholdMs;
}
public PerformanceBenchmarkingFilter() {
this(800L); // Default 800ms SLA warning ceiling
}
@Override
public Response filter(FilterableRequestSpecification requestSpec,
FilterableResponseSpecification responseSpec,
FilterContext ctx) {
long startTime = System.currentTimeMillis();
// Dispatch request downstream to server
Response response = ctx.next(requestSpec, responseSpec);
long elapsedTime = System.currentTimeMillis() - startTime;
String endpoint = requestSpec.getMethod() + " " + requestSpec.getDerivedPath();
if (elapsedTime > warningThresholdMs) {
System.err.printf("[PERFORMANCE WARNING] %s took %d ms (Threshold: %d ms)%n",
endpoint, elapsedTime, warningThresholdMs);
} else {
System.out.printf("[PERFORMANCE SLA PASS] %s completed in %d ms%n",
endpoint, elapsedTime);
}
return response;
}
}
package com.nikita.restassured.filters;
import io.restassured.filter.Filter;
import io.restassured.filter.FilterContext;
import io.restassured.response.Response;
import io.restassured.specification.FilterableRequestSpecification;
import io.restassured.specification.FilterableResponseSpecification;
import java.util.regex.Pattern;
public class PiiMaskingFilter implements Filter {
// Regex patterns for sensitive JSON keys
private static final Pattern PASSWORD_PATTERN = Pattern.compile("(?i)(\"password\"\\s*:\\s*\")[^\"]+(\")");
private static final Pattern CARD_PATTERN = Pattern.compile("(?i)(\"cardNumber\"\\s*:\\s*\")[^\"]+(\")");
@Override
public Response filter(FilterableRequestSpecification requestSpec,
FilterableResponseSpecification responseSpec,
FilterContext ctx) {
System.out.println("[SECURITY SANITIZER] Outbound Request: " + requestSpec.getMethod() + " " + requestSpec.getURI());
// Sanitize headers: Redact Authorization tokens in logs
if (requestSpec.getHeaders().hasHeaderWithName("Authorization")) {
System.out.println(" Header: Authorization = Bearer **********[REDACTED]**********");
}
// Sanitize body: Redact passwords and financial card numbers
if (requestSpec.getBody() != null) {
String rawBody = requestSpec.getBody().toString();
String sanitizedBody = PASSWORD_PATTERN.matcher(rawBody).replaceAll("$1********[MASKED]$2");
sanitizedBody = CARD_PATTERN.matcher(sanitizedBody).replaceAll("$1************1234[MASKED]$2");
System.out.println(" Sanitized Payload: " + sanitizedBody);
}
// The actual unmasked request proceeds over the secure wire to the server:
return ctx.next(requestSpec, responseSpec);
}
}
OrderedFilter to define strict priority levels, ensuring logging and authentication interceptors run in the correct order.
package com.nikita.restassured.filters;
import io.restassured.filter.FilterContext;
import io.restassured.filter.OrderedFilter;
import io.restassured.response.Response;
import io.restassured.specification.FilterableRequestSpecification;
import io.restassured.specification.FilterableResponseSpecification;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
// Interceptor 1: Runs FIRST (Lowest order value = Highest priority)
class PriorityOneTracingFilter implements OrderedFilter {
@Override
public int getOrder() {
return 1; // Highest priority
}
@Override
public Response filter(FilterableRequestSpecification req, FilterableResponseSpecification res, FilterContext ctx) {
System.out.println("[Order 1] Executing Tracing Header Interceptor");
req.header("X-Filter-Order-1", "Executed-First");
return ctx.next(req, res);
}
}
// Interceptor 2: Runs SECOND
class PriorityTwoAuthFilter implements OrderedFilter {
@Override
public int getOrder() {
return 2; // Executes after Order 1
}
@Override
public Response filter(FilterableRequestSpecification req, FilterableResponseSpecification res, FilterContext ctx) {
System.out.println("[Order 2] Executing Auth Verification Interceptor");
req.header("X-Filter-Order-2", "Executed-Second");
return ctx.next(req, res);
}
}
public class OrderedFilterExecutionTest {
@Test(description = "Verify OrderedFilter enforces execution order based on getOrder() return value")
public void testOrderedFiltersExecution() {
given()
.baseUri("https://staging-api.nikita-infotech.com/v1")
// Registered in reverse order to prove OrderedFilter sorts by getOrder():
.filter(new PriorityTwoAuthFilter())
.filter(new PriorityOneTracingFilter())
.when()
.get("/health")
.then()
.statusCode(200);
System.out.println("[β] Verified filter chain executed in exact order (Priority 1 then Priority 2).");
}
}
AllureRestAssured.
// ==============================================================================
// STEP 1: MAVEN DEPENDENCY REQUIRED (pom.xml)
// ==============================================================================
// <dependency>
// <groupId>io.qameta.allure</groupId>
// <artifactId>allure-rest-assured</artifactId>
// <version>2.27.0</version>
// <scope>test</scope>
// </dependency>
package com.nikita.restassured.filters;
import io.qameta.allure.restassured.AllureRestAssured;
import io.restassured.builder.RequestSpecBuilder;
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 AllureReportingFilterTest {
private RequestSpecification allureReportSpec;
@BeforeClass
public void setupAllureFilter() {
// Instantiate AllureRestAssured filter with customized attachment templates
AllureRestAssured allureFilter = new AllureRestAssured()
.setRequestTemplate("http-request.ftl")
.setResponseTemplate("http-response.ftl");
allureReportSpec = new RequestSpecBuilder()
.setBaseUri("https://staging-api.nikita-infotech.com/v1")
.addFilter(allureFilter) // Attaches all wire packets directly to Allure test steps!
.build();
System.out.println("[*] AllureRestAssured attachment filter bound to RequestSpecification.");
}
@Test(description = "Execute request with automatic Allure report request/response attachments")
public void testAllureAttachmentGeneration() {
given()
.spec(allureReportSpec)
.pathParam("studentId", "STU-88219")
.when()
.get("/students/{studentId}")
.then()
.statusCode(200)
.body("status", equalTo("SUCCESS"));
System.out.println("[β] Wire request and response saved to target/allure-results automatically.");
}
}
REST ASSURED FILTER & INTERCEPTION SPECIFICATION MATRIX:
βββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββ¬βββββββββββββββββββ¬ββββββββββββββββββββββββββββββββ
β INTERFACE / COMPONENT β METHOD SIGNATURE β RETURN TYPE β PRIMARY OPERATIONAL PURPOSE β
βββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββΌββββββββββββββββββββββββββββββββ€
β Filter β filter(reqSpec, resSpec, ctx)β Response β Core interceptor contract β
β OrderedFilter β getOrder() β int (Priority) β Enforces filter run sequence β
β FilterContext β ctx.next(reqSpec, resSpec) β Response β Dispatches to next in chain β
β FilterableRequestSpec β reqSpec.header(name, value) β RequestSpec β Injects/mutates outbound data β
β FilterableRequestSpec β reqSpec.removeHeader(name) β RequestSpec β Strips expired headers β
β FilterableRequestSpec β reqSpec.getURI() β String (URI) β Inspects target URL in logs β
β FilterableRequestSpec β reqSpec.getBody() β Object (Body) β Accesses raw payload for PII β
β FilterableResponseSpec β resSpec.hasHeaderAssertions()β Boolean β Inspects response assertions β
β Response (Returned) β response.getStatusCode() β int (Status) β Checks status for 401 retry β
β AllureRestAssured β new AllureRestAssured() β Filter instance β Auto-attaches logs to Allure β
β RestAssured.filters() β RestAssured.filters(f1, f2) β void β Registers global filter chain β
βββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββ΄βββββββββββββββββββ΄ββββββββββββββββββββββββββββββββ€
β TOP 5 CUSTOM FILTER BEST PRACTICES: β
β 1. Centralize cross-cutting concerns: Move correlation IDs, timing, and auth refresh into filters. β
β 2. Use OrderedFilter for deterministic execution: Control execution priority with getOrder(). β
β 3. Implement self-healing 401 token refresh: Intercept 401s, fetch a fresh token, and retry in-flight. β
β 4. Mask sensitive PII in console logs: Redact passwords and tokens before printing to build logs. β
β 5. Attach AllureRestAssured for rich reporting: Provide full request/response wire logs to developers. β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ