What is Preemptive Authentication?
In preemptive authentication, the client sends the credentials (username & password) in the very first request, rather than waiting for the server to challenge it (with a 401 unauthorized response).
This can improve performance by skipping an extra request-response cycle.
To use preemptive basic auth in Rest Assured:
- Use
.auth().preemptive().basic(username, password)
- This sends the
Authorization
header directly with the GET request.
- You can validate response data with assertions.
API to be tested:
https://postman-echo.com/basic-auth This endpoint requires Basic Authentication Username: "postman" Password: "password"
Java Code using Rest Assured:
import io.restassured.RestAssured; import io.restassured.response.Response; import static io.restassured.RestAssured.*; import static org.hamcrest.Matchers.*; public class PreemptiveAuthTest { public static void main(String[] args) { // Base URI RestAssured.baseURI = "https://postman-echo.com"; // Preemptive Basic Auth GET Request given() .auth().preemptive().basic("postman", "password") .when() .get("/basic-auth") .then() .statusCode(200) .body("authenticated", equalTo(true)) .log().all(); } }
Output:
{ "authenticated": true }
Explanation:
Line | Purpose |
---|---|
.auth().preemptive().basic(...) | Sends credentials proactively without waiting for a challenge |
.get("/basic-auth") | Executes the GET request |
.statusCode(200) | Asserts the response status is OK |
.body("authenticated", equalTo(true)) | Asserts that authentication was successful |
.log().all() | Logs full response details to console |
No comments:
Post a Comment