Answer
Handling Cookies in Rest Assured
Some APIs use cookies for session management instead of Bearer tokens. Rest Assured provides full cookie support.
Sending a Cookie in Request
Java
@Test
public void testWithSingleCookie() {
given()
.cookie("session_id", "abc123xyz")
.when()
.get("/api/dashboard")
.then()
.statusCode(200);
}
Sending Multiple Cookies
Java
@Test
public void testWithMultipleCookies() {
given()
.cookie("session_id", "abc123xyz")
.cookie("user_role", "admin")
.cookie("locale", "en-US")
.when()
.get("/api/dashboard")
.then()
.statusCode(200);
}
Extract Cookies from Response
Java
@Test
public void testExtractCookiesFromLoginResponse() {
// Step 1: Login and get session cookie
Response loginResponse = given()
.contentType(ContentType.JSON)
.body("{ \"username\": \"admin\", \"password\": \"pass\" }")
.when()
.post("/api/auth/login");
// Extract the session cookie
String sessionCookie = loginResponse.getCookie("session_id");
System.out.println("Session Cookie: " + sessionCookie);
// Step 2: Use the cookie in next request
given()
.cookie("session_id", sessionCookie)
.when()
.get("/api/profile")
.then()
.statusCode(200);
}
Get All Cookies from Response
Java
@Test
public void testGetAllResponseCookies() {
Response response = given()
.when()
.get("/api/users");
// Get all cookies as a map
Map<String, String> cookies = response.getCookies();
cookies.forEach((name, value) ->
System.out.println(name + " = " + value));
// Get a specific cookie
String token = response.getCookie("auth_token");
}
Validate Cookie Properties
Java
@Test
public void testCookieProperties() {
given()
.when()
.post("/api/auth/login")
.then()
.statusCode(200)
.cookie("session_id") // cookie exists
.cookie("session_id", notNullValue()) // not null
.cookie("session_id", not(emptyOrNullString())); // not empty
}
Using DetailedCookie for Full Attributes
Java
@Test
public void testCookieAttributesSecure() {
DetailedCookie sessionCookie = given()
.when()
.post("/api/login")
.then()
.extract()
.detailedCookie("session_id");
assertTrue(sessionCookie.isSecured(), "Cookie should be Secure");
assertTrue(sessionCookie.isHttpOnly(), "Cookie should be HttpOnly");
assertEquals(sessionCookie.getPath(), "/");
}
Security Checks for Cookies
| Attribute | Importance | Test |
|---|---|---|
Secure | Cookie only sent over HTTPS | Must be true in production |
HttpOnly | JS cannot access the cookie | Prevents XSS theft |
SameSite | CSRF protection | Should be Strict or Lax |
