π‘οΈ Machine-to-Machine Authorization, Token Harvesting & In-Memory Caching
In enterprise microservice architectures, background daemons, automated testing suites, and backend workers do not operate on behalf of interactive human users. Instead, they authenticate directly against authorization servers using the OAuth 2.0 Client Credentials Grant (RFC 6749 Section 4.4). Under this flow, the client acts as the resource owner, exchanging its confidential client_id and client_secret (via application/x-www-form-urlencoded form parameters or HTTP Basic Authentication headers) for an ephemeral Bearer Access Token. In production test automation frameworks, re-authenticating and requesting a fresh token before every single test scenario degrades execution speed and triggers rate-limiting thresholds. By implementing a Thread-Safe Token Manager with TTL Caching in REST Assured, automation engineers harvest access tokens once, reuse them across parallel TestNG worker threads until near-expiry, and transparently re-authenticate when tokens expire.
OAUTH 2.0 CLIENT CREDENTIALS GRANT (RFC 6749 SECTION 4.4) LIFECYCLE:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β STEP 1: CLIENT AUTHENTICATION & TOKEN REQUEST β
β POST /oauth/v2/token HTTP/1.1 β
β Host: auth.nikita-infotech.com β
β Content-Type: application/x-www-form-urlencoded β
β β
β Payload: β
β grant_type=client_credentials&client_id=sdet-worker-pune&client_secret=Sec#2026&scope=read:allβ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ (Validated by OAuth2 Authorization Server)
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β STEP 2: AUTHORIZATION SERVER RESPONSE β
β HTTP/1.1 200 OK β
β Content-Type: application/json;charset=UTF-8 β
β Cache-Control: no-store β
β Pragma: no-cache β
β β
β { β
β "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.payload.signature", β
β "token_type": "Bearer", β
β "expires_in": 3600, β
β "scope": "read:all write:all" β
β } β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ (Extracted & Stored in In-Memory Token Cache)
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β STEP 3: DISPATCH REQUEST TO RESOURCE SERVER (With Extracted Bearer Token) β
β GET /v1/students/STU-88219 HTTP/1.1 β
β Host: staging-api.nikita-infotech.com β
β Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.payload.signature β
β Accept: application/json β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ (Resource Server Validates Signature & Claims)
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β STEP 4: RESOURCE SERVER RETURNS DATA (HTTP 200 OK) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
client_id, client_secret, and grant_type=client_credentials directly inside the URL-encoded POST body.
package com.nikita.restassured.oauth2;
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 BasicClientCredentialsTest {
private static final String AUTH_SERVER = "https://auth.nikita-infotech.com";
@Test(description = "Harvest OAuth 2.0 token using client credentials passed in form body")
public void testHarvestTokenViaBodyCredentials() {
String accessToken = given()
.baseUri(AUTH_SERVER)
.contentType(ContentType.URLENC.withCharset("UTF-8"))
// RFC 6749 Mandatory Form Parameters
.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()
// 1. Validate HTTP 200 OK
.statusCode(200)
.contentType(ContentType.JSON)
// 2. Validate RFC 6749 compliance envelope
.body("token_type", equalToIgnoringCase("Bearer"))
.body("access_token", notNullValue())
.body("expires_in", greaterThan(0))
.body("scope", containsString("students:read"))
// 3. Extract access token string
.extract()
.path("access_token");
System.out.println("[+] Successfully harvested Bearer token: " + accessToken.substring(0, 20) + "...");
Assert.assertNotNull(accessToken, "Failed to extract access_token from response!");
}
}
client_id and client_secret encoded in the Authorization: Basic ... header while keeping grant_type in the form body.
package com.nikita.restassured.oauth2;
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 BasicHeaderClientAuthTest {
private static final String AUTH_SERVER = "https://auth.nikita-infotech.com";
@Test(description = "Authenticate client via HTTP Basic header and transmit grant_type in body")
public void testHarvestTokenViaBasicHeaderAuth() {
String clientId = "sdet-automation-worker";
String clientSecret = "Secret#Enterprise2026Key";
String accessToken = given()
.baseUri(AUTH_SERVER)
// RFC 6749 Section 2.3.1: Client credentials sent via HTTP Basic header
.auth().preemptive().basic(clientId, clientSecret)
.contentType(ContentType.URLENC.withCharset("UTF-8"))
// Only grant_type and optional scope remain in the form body:
.formParam("grant_type", "client_credentials")
.formParam("scope", "students:admin")
.log().ifValidationFails()
.when()
.post("/oauth/v2/token")
.then()
.statusCode(200)
.contentType(ContentType.JSON)
.body("token_type", equalToIgnoringCase("Bearer"))
.body("access_token", notNullValue())
.extract()
.path("access_token");
System.out.println("[+] Token acquired using HTTP Basic client authentication: " + accessToken.substring(0, 15) + "...");
Assert.assertNotNull(accessToken);
}
}
package com.nikita.restassured.oauth2;
import io.restassured.http.ContentType;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
public class EndToEndM2MWorkflowTest {
private static final String IDP_URL = "https://auth.nikita-infotech.com";
private static final String API_GATEWAY = "https://staging-api.nikita-infotech.com/v1";
@Test(description = "End-to-End M2M: Fetch OAuth2 token from IdP and consume on API Gateway")
public void testCompleteM2mPipeline() {
// =====================================================================
// STEP 1: HARVEST BEARER TOKEN FROM IDENTITY PROVIDER
// =====================================================================
String bearerToken = given()
.baseUri(IDP_URL)
.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")
.when()
.post("/oauth/v2/token")
.then()
.statusCode(200)
.extract()
.path("access_token");
System.out.println("[Step 1] Harvested Bearer Token from IdP: " + bearerToken.substring(0, 18) + "...");
// =====================================================================
// STEP 2: ACCESS PROTECTED RESOURCE GATEWAY USING EXTRACTED TOKEN
// =====================================================================
given()
.baseUri(API_GATEWAY)
// Forward harvested token via RFC 6750 Bearer Authorization header:
.header("Authorization", "Bearer " + bearerToken)
.pathParam("studentId", "STU-88219")
.when()
.get("/students/{studentId}")
.then()
.statusCode(200)
.body("status", equalTo("SUCCESS"))
.body("data.id", equalTo("STU-88219"))
.body("data.fullName", equalTo("Nikita Sharma"));
System.out.println("[Step 2] Protected resource retrieved successfully using harvested token.");
}
}
package com.nikita.restassured.oauth2;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import io.restassured.path.json.JsonPath;
import java.time.Instant;
public class OAuth2TokenManager {
private static final String IDP_URL = "https://auth.nikita-infotech.com";
private static final String CLIENT_ID = "sdet-automation-worker";
private static final String CLIENT_SECRET = "Secret#Enterprise2026Key";
// In-Memory Token Cache Variables (Volatile for cross-thread visibility)
private static volatile String cachedToken;
private static volatile Instant tokenExpiryTime = Instant.MIN;
// Buffer margin (in seconds) to refresh token before actual expiration
private static final long EXPIRY_BUFFER_SECONDS = 60L;
/**
* Retrieves an active Bearer token. Returns the cached token if still valid,
* or requests a new one if expired or uninitialized.
*/
public static String getAccessToken() {
if (isTokenExpired()) {
synchronized (OAuth2TokenManager.class) {
if (isTokenExpired()) {
renewToken();
}
}
}
return cachedToken;
}
private static boolean isTokenExpired() {
return cachedToken == null || Instant.now().isAfter(tokenExpiryTime.minusSeconds(EXPIRY_BUFFER_SECONDS));
}
private static void renewToken() {
System.out.println("[*] OAuth2TokenManager: Token expired or null. Requesting fresh token from IdP...");
String responseBody = RestAssured.given()
.baseUri(IDP_URL)
.contentType(ContentType.URLENC.withCharset("UTF-8"))
.formParam("grant_type", "client_credentials")
.formParam("client_id", CLIENT_ID)
.formParam("client_secret", CLIENT_SECRET)
.formParam("scope", "students:read students:write")
.when()
.post("/oauth/v2/token")
.then()
.statusCode(200)
.extract()
.asString();
JsonPath json = new JsonPath(responseBody);
cachedToken = json.getString("access_token");
long expiresInSeconds = json.getLong("expires_in");
tokenExpiryTime = Instant.now().plusSeconds(expiresInSeconds);
System.out.println("[*] OAuth2TokenManager: Acquired new token. Valid for " + expiresInSeconds + " seconds (Expires at: " + tokenExpiryTime + ")");
}
// Force invalidation for testing re-authentication
public static synchronized void invalidateToken() {
cachedToken = null;
tokenExpiryTime = Instant.MIN;
System.out.println("[!] OAuth2TokenManager: Token cache forcibly invalidated.");
}
}
OAuth2TokenManager.getAccessToken() directly into a centralized RequestSpecBuilder factory, so test classes inherit valid Bearer authentication with zero manual token handling.
package com.nikita.restassured.oauth2;
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 SpecIntegratedOAuth2Test {
// Factory method building pre-authenticated specification
public static RequestSpecification getAuthenticatedStudentSpec() {
return new RequestSpecBuilder()
.setBaseUri("https://staging-api.nikita-infotech.com")
.setBasePath("/v1/students")
.setContentType(ContentType.JSON)
.setAccept(ContentType.JSON)
// Automatically pulls active or cached token from manager:
.addHeader("Authorization", "Bearer " + OAuth2TokenManager.getAccessToken())
.addHeader("X-Tenant-Key", "MAHARASHTRA_PUNE_01")
.build();
}
@Test(description = "Execute API test inheriting authentication transparently from specification")
public void testStudentQueryWithAutoAuth() {
given()
// Bind pre-authenticated specification
.spec(getAuthenticatedStudentSpec())
.pathParam("studentId", "STU-88219")
.when()
.get("/{studentId}")
.then()
.statusCode(200)
.body("status", equalTo("SUCCESS"))
.body("data.id", equalTo("STU-88219"));
System.out.println("[β] Test executed cleanly with zero manual token fetching in test body.");
}
}
read:students vs. admin:all) and verifies that resource servers enforce access control policies based on the granted token scopes.
package com.nikita.restassured.oauth2;
import io.restassured.http.ContentType;
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 OAuth2ScopeValidationTest {
private static final String IDP_URL = "https://auth.nikita-infotech.com";
private static final String API_GATEWAY = "https://staging-api.nikita-infotech.com/v1";
// Helper to fetch token with explicit scope request
private String fetchTokenWithScope(String requestedScope) {
return given()
.baseUri(IDP_URL)
.contentType(ContentType.URLENC.withCharset("UTF-8"))
.formParam("grant_type", "client_credentials")
.formParam("client_id", "sdet-automation-worker")
.formParam("client_secret", "Secret#Enterprise2026Key")
.formParam("scope", requestedScope)
.when()
.post("/oauth/v2/token")
.then()
.statusCode(200)
.extract()
.path("access_token");
}
@Test(description = "Verify read-only scoped token succeeds on GET but fails on DELETE with 403 Forbidden")
public void testReadOnlyScopeBoundary() {
// Step 1: Harvest token with read-only scope
String readOnlyToken = fetchTokenWithScope("students:read");
// Step 2: GET operation must succeed
given()
.baseUri(API_GATEWAY)
.header("Authorization", "Bearer " + readOnlyToken)
.pathParam("studentId", "STU-88219")
.when()
.get("/students/{studentId}")
.then()
.statusCode(200)
.body("status", equalTo("SUCCESS"));
System.out.println("[β] GET succeeded with students:read scope.");
// Step 3: DELETE operation must fail with 403 Forbidden due to missing 'students:delete' scope
given()
.baseUri(API_GATEWAY)
.header("Authorization", "Bearer " + readOnlyToken)
.pathParam("studentId", "STU-88219")
.when()
.delete("/students/{studentId}")
.then()
.statusCode(403)
.body("title", equalTo("Forbidden"))
.body("detail", containsString("Insufficient scope: requires 'students:delete'"));
System.out.println("[β] DELETE rejected with 403 Forbidden on read-only token.");
}
}
401 Unauthorized responses, invalidates the OAuth2TokenManager cache, requests a new token, and replays the original request transparently.
package com.nikita.restassured.oauth2;
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 OAuth2RetryFilter implements Filter {
@Override
public Response filter(FilterableRequestSpecification requestSpec,
FilterableResponseSpecification responseSpec,
FilterContext ctx) {
// Ensure request has a Bearer token attached
if (!requestSpec.getHeaders().hasHeaderWithName("Authorization")) {
requestSpec.header("Authorization", "Bearer " + OAuth2TokenManager.getAccessToken());
}
// Execute original request
Response response = ctx.next(requestSpec, responseSpec);
// If gateway returns 401 Unauthorized, token has been revoked or expired on server:
if (response.getStatusCode() == 401) {
System.out.println("[!] OAuth2RetryFilter: Intercepted 401 Unauthorized. Evicting token cache and retrying...");
// Invalidate cache and fetch fresh token
OAuth2TokenManager.invalidateToken();
String freshToken = OAuth2TokenManager.getAccessToken();
// Replace Authorization header with fresh token
requestSpec.removeHeader("Authorization");
requestSpec.header("Authorization", "Bearer " + freshToken);
// Re-execute the request with fresh token
System.out.println("[*] OAuth2RetryFilter: Re-dispatching request with refreshed token...");
response = ctx.next(requestSpec, responseSpec);
}
return response;
}
}
/token endpoint. Validates RFC 6749 error responses: invalid client credentials (HTTP 401 invalid_client), unsupported grant types (HTTP 400 unsupported_grant_type), and invalid scopes (HTTP 400 invalid_scope).
package com.nikita.restassured.oauth2;
import io.restassured.http.ContentType;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
public class NegativeOAuth2TokenTest {
private static final String IDP_URL = "https://auth.nikita-infotech.com";
@Test(description = "Verify invalid client_secret produces HTTP 401 with error=invalid_client")
public void testInvalidClientSecretProduces401() {
given()
.baseUri(IDP_URL)
.contentType(ContentType.URLENC.withCharset("UTF-8"))
.formParam("grant_type", "client_credentials")
.formParam("client_id", "sdet-automation-worker")
.formParam("client_secret", "WRONG_SECRET_VALUE")
.when()
.post("/oauth/v2/token")
.then()
.statusCode(401)
.contentType(ContentType.JSON)
.body("error", equalTo("invalid_client"))
.body("error_description", equalTo("Client authentication failed"));
System.out.println("[β] Verified 401 invalid_client error on bad secret.");
}
@Test(description = "Verify invalid grant_type produces HTTP 400 with error=unsupported_grant_type")
public void testUnsupportedGrantTypeProduces400() {
given()
.baseUri(IDP_URL)
.contentType(ContentType.URLENC.withCharset("UTF-8"))
.formParam("grant_type", "invalid_grant_name")
.formParam("client_id", "sdet-automation-worker")
.formParam("client_secret", "Secret#Enterprise2026Key")
.when()
.post("/oauth/v2/token")
.then()
.statusCode(400)
.body("error", equalTo("unsupported_grant_type"));
System.out.println("[β] Verified 400 unsupported_grant_type on broken grant_type.");
}
@Test(description = "Verify unapproved scope request produces HTTP 400 with error=invalid_scope")
public void testInvalidScopeProduces400() {
given()
.baseUri(IDP_URL)
.contentType(ContentType.URLENC.withCharset("UTF-8"))
.formParam("grant_type", "client_credentials")
.formParam("client_id", "sdet-automation-worker")
.formParam("client_secret", "Secret#Enterprise2026Key")
.formParam("scope", "super_admin_unapproved_scope")
.when()
.post("/oauth/v2/token")
.then()
.statusCode(400)
.body("error", equalTo("invalid_scope"));
System.out.println("[β] Verified 400 invalid_scope on unauthorized scope request.");
}
}
OAUTH 2.0 CLIENT CREDENTIALS SPECIFICATION MATRIX:
βββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββ¬βββββββββββββββββββ¬ββββββββββββββββββββββββββββββββ
β COMPONENT / PARAMETER β REST ASSURED DSL METHOD β RFC STANDARD β PRIMARY OPERATIONAL PURPOSE β
βββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββΌββββββββββββββββββββββββββββββββ€
β Endpoint URL β POST /oauth/v2/token β RFC 6749 Sec 3.2 β Token endpoint for harvesting β
β Content-Type β ContentType.URLENC (UTF-8) β RFC 6749 Sec 4.4 β Mandatory form-url-encoded β
β grant_type β .formParam("grant_type", ..) β RFC 6749 Sec 4.4 β Value: "client_credentials" β
β client_id (Body) β .formParam("client_id", ..) β RFC 6749 Sec 4.4 β Identifies client application β
β client_secret (Body) β .formParam("client_secret") β RFC 6749 Sec 4.4 β Confidential client secret β
β client_id/secret (Head) β .auth().preemptive().basic() β RFC 6749 Sec 2.3 β Basic Auth client credentials β
β scope β .formParam("scope", ..) β RFC 6749 Sec 3.3 β Space-delimited permissions β
β access_token β extract().path("access_tok") β RFC 6749 Sec 5.1 β Bearer access token string β
β token_type β equalToIgnoringCase("Bearer")β RFC 6749 Sec 5.1 β Must be "Bearer" β
β expires_in β extract().path("expires_in") β RFC 6749 Sec 5.1 β Lifetime in seconds (e.g 3600)β
β Bearer Authorization β .header("Authorization", ..) β RFC 6750 Sec 2.1 β "Bearer <access_token>" β
β Token Caching β OAuth2TokenManager.java β In-Memory TTL β Prevents redundant /token reqsβ
β 401 Self-Healing Filter β OAuth2RetryFilter.java β REST Assured Fltrβ Re-harvests token on 401 β
βββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββ΄βββββββββββββββββββ΄ββββββββββββββββββββββββββββββββ€
β TOP 5 OAUTH 2.0 CLIENT CREDENTIALS BEST PRACTICES: β
β 1. Cache tokens in memory with TTL: Avoid requesting a fresh token on every test; reuse until expiry. β
β 2. Use a safety buffer for expiration: Refresh tokens 60 seconds before actual expires_in timestamp. β
β 3. Prefer HTTP Basic client auth (RFC 6749 Sec 2.3.1): Keep credentials out of the POST request body. β
β 4. Implement a self-healing 401 filter: Handle unexpected mid-run token revocations automatically. β
β 5. Test negative RFC 6749 errors: Verify 401 invalid_client, 400 unsupported_grant_type & invalid_scope. β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ