Form authentication is typically used by web applications that present a login form where users enter credentials (like username/password), and those are sent as part of the form (usually POST request). Once the server validates the credentials, it may set a session cookie or token which is used for subsequent requests.
How Form Auth Works in Rest Assured:
Rest Assured provides:
.formAuth(loginUrl, usernameField, passwordField, username, password)
This simulates a form-based login by:
- Making a POST request to the login URL
- Submitting the credentials using field names (like
username
,password
) - Then it stores session/cookie for further requests like
GET
,POST
, etc.
Sample API for Form Auth
We will use: https://the-internet.herokuapp.com/login
(a public test site)
Login URL:
https://the-internet.herokuapp.com/authenticate
Username Field Name: username
Password Field Name: password
Username: tomsmith
Password: SuperSecretPassword!
Java Code with Rest Assured:
import io.restassured.RestAssured; import io.restassured.filter.session.SessionFilter; import static io.restassured.RestAssured.*; public class FormAuthExample { public static void main(String[] args) { // Create session filter to maintain session across requests SessionFilter session = new SessionFilter(); // Step 1: Log in using form-based auth given() .baseUri("https://the-internet.herokuapp.com") .filter(session) .formParam("username", "tomsmith") .formParam("password", "SuperSecretPassword!") .when() .post("/authenticate") .then() .statusCode(302); // Expect redirect on successful login // Step 2: Access GET API after login given() .baseUri("https://the-internet.herokuapp.com") .filter(session) .when() .get("/secure") .then() .statusCode(200) .log().body(); // Print response to confirm access } }
Maven Dependencies
<dependencies> <dependency> <groupId>io.rest-assured</groupId> <artifactId>rest-assured</artifactId> <version>5.4.0</version> <scope>test</scope> </dependency> </dependencies>
No comments:
Post a Comment