What is Form Authentication?
- Form Authentication is a type of authentication where the user provides credentials (like username and password) through an HTML form (usually a login page).
- The credentials are sent to the server (often via POST request) → if valid, the server creates a session (often maintained using cookies or tokens) → and the client can then access protected resources.
Form-based login is very common in web applications.
-
Supply the username and password that the login form requires.
-
Specify the login page (form action URL), and the parameter names for username and password fields (e.g.,
username,password).
-
Rest Assured submits the credentials just like a browser submitting a login form.
4. Handle cookies/session
-
Once the server authenticates, it typically returns a session cookie or auth token.
-
Rest Assured automatically manages these cookies so subsequent requests can use the authenticated session.
-
Now you can send API requests that require authentication and verify the response.
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/authenticateUsername Field Name: username
Password Field Name: password
Username: tomsmith
Password: SuperSecretPassword!
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 } }
<dependencies> <dependency> <groupId>io.rest-assured</groupId> <artifactId>rest-assured</artifactId> <version>5.4.0</version> <scope>test</scope> </dependency> </dependencies>
Suggested Posts:
1. Test Status Line of API in RestAssured
2. Test Form Authentication in RestAssured
3. Test DELETE API in RestAssured
4. First RestAssured Code to Test API
5. How to Test Basic Authentication in RestAssured