π 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.
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 β
βββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββ
x-api-key or X-Tenant-Key). Demonstrates verifying authentication, quota headers, and successful entity access.
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.");
}
}
?api_key=...). Demonstrates testing services where third-party webhooks, public telemetry, or mapping APIs ingest authentication via query criteria.
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.");
}
}
.auth().oauth2(token) method against explicit .header("Authorization", "Bearer " + token) injection. Demonstrates that both patterns yield identical HTTP wire packets.
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.");
}
}
client_credentials, extracts the minted access token from the JSON response, and chains that token into downstream API requests.
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.");
}
}
JsonPath, and asserts identity attributes and roles.
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.");
}
}
exp < current_epoch) with HTTP 401 Unauthorized and an expired_token error code.
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.");
}
}
RequestSpecBuilder factory that dynamically injects Bearer tokens or API keys into pre-configured 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.");
}
}
HTTP 401), malformed garbage Bearer tokens, and valid tokens with insufficient scope permissions (HTTP 403 Forbidden).
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.");
}
}
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. β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ