Mastering API Authentication in Rest Assured
Authentication and Authorization are critical components of web application security. In automated API testing, handling tokens, credentials, and OAuth workflows efficiently ensures your test suite runs securely and reliably. In this guide, we break down every API authentication strategy you will encounter in real-world testing using Rest Assured.
1. Introduction to API Authentication
API authentication verifies the client's identity before allowing access to resources. While Authentication (AuthN) asks "Who are you?", Authorization (AuthZ) asks "What permissions do you have?".
2. Basic Authentication in Rest Assured
Basic Auth passes a Base64-encoded string formatted as username:password inside the HTTP Authorization header.
Preemptive vs. Digest Basic Auth
Rest Assured supports both standard and preemptive Basic Auth. Preemptive sends credentials right away without waiting for an initial 401 Unauthorized challenge from the server.
// Preemptive Basic Auth Example
given()
.auth().preemptive().basic("adminUser", "secretPassword123")
.when()
.get("https://api.way2testing.com/secure/dashboard")
.then()
.statusCode(200);
3. Bearer Tokens, 4. Generation & Extraction, and 5. Token Passing
Bearer Tokens are cryptographic tokens issued by an identity provider. Clients attach the token to the header as: Authorization: Bearer <TOKEN>.
Extracting & Reusing Tokens Pattern:
// Step 1: Login & Extract Access Token
String accessToken = given()
.contentType(ContentType.JSON)
.body("{\"username\": \"testuser\", \"password\": \"pass123\"}")
.when()
.post("https://api.way2testing.com/auth/login")
.then()
.statusCode(200)
.extract().path("access_token");
// Step 2: Pass Token to Downstream Endpoint
given()
.header("Authorization", "Bearer " + accessToken)
.when()
.get("https://api.way2testing.com/user/profile")
.then()
.statusCode(200);
6. OAuth 2.0 Authentication & 7. Grant Types Explained
OAuth 2.0 is an authorization framework that provides delegated access to resources without sharing credentials directly.
Common Grant Types Matrix
- Client Credentials Grant: Used for service-to-service automation tests (requires
client_idandclient_secret). - Authorization Code Grant: Used for user-facing web applications (involves browser redirects).
- Resource Owner Password Credentials: Used when trusted apps exchange user credentials directly for tokens.
- Refresh Token Grant: Exchanged to retrieve new access tokens when old ones expire.
// OAuth 2.0 Client Credentials Request in Rest Assured
String oauthToken = given()
.formParam("grant_type", "client_credentials")
.formParam("client_id", "myClientId")
.formParam("client_secret", "myClientSecret")
.when()
.post("https://api.way2testing.com/oauth/v2/token")
.then()
.statusCode(200)
.extract().path("access_token");
// Using rest-assured oauth2 shortcut method
given()
.auth().oauth2(oauthToken)
.when()
.get("https://api.way2testing.com/v2/reports")
.then()
.statusCode(200);
8. How to Test JWT Tokens & 9. Refresh Tokens and Token Expiry
JSON Web Tokens (JWT) consist of three base64-encoded parts: Header.Payload.Signature.
Validating JWT Tokens in Automation:
- Claims Verification: Verify standard claim fields such as
iss(issuer),sub(subject), andexp(expiration timestamp). - Expired Token Handling: Validate that sending an expired token results in an HTTP
401 Unauthorizedresponse. - Refresh Flow: Perform a POST request to
/auth/refreshwith a refresh token to generate a freshaccess_tokenbefore continuing test execution.
10. How to Handle API Keys, Cookies and CSRF Tokens
Beyond Bearer and OAuth headers, web applications use additional mechanisms to secure stateful and stateless requests:
1. API Keys in Query or Headers
given()
.header("x-api-key", "a1b2c3d4e5f6") // Custom Header API Key
.queryParam("api_key", "secret123") // Query Param API Key
.when()
.get("https://api.way2testing.com/v1/data")
.then()
.statusCode(200);
2. CSRF (Cross-Site Request Forgery) Token Handling
State-changing endpoints (POST/PUT/DELETE) often require a CSRF token extracted from an initial GET response cookie or HTML form header.
// Extract CSRF Token and Cookie
Response response = get("https://api.way2testing.com/form-init");
String csrfToken = response.getHeader("X-CSRF-TOKEN");
String sessionCookie = response.getCookie("JSESSIONID");
// Pass both CSRF token and session cookie to the POST endpoint
given()
.cookie("JSESSIONID", sessionCookie)
.header("X-CSRF-TOKEN", csrfToken)
.formParam("action", "transfer_funds")
.when()
.post("https://api.way2testing.com/transfer")
.then()
.statusCode(200);
No comments:
Post a Comment