Showing posts with label Rest Assured Tutorial. Show all posts
Showing posts with label Rest Assured Tutorial. Show all posts

How to test Preemptive Authentication in Rest Assured

  



What is Preemptive Authentication?


Preemptive authentication in APIs is an optimization technique where the client (like a browser or an application) sends authentication credentials with the very first request to a protected resource, before the server has explicitly asked for them.

It's based on the assumption that the resource is protected and will require credentials. This contrasts with the more common challenge-response (or reactive) authentication, where the client first makes an unauthenticated request, the server responds with an error (e.g., HTTP 401 Unauthorized) and a challenge (ex: a WWW-Authenticate header), and then the client makes a second, authenticated request.


More about Preemptive Authentication

1. Mechanism
  • Client's First Request: The client includes the authentication header (e.g., Authorization: Basic [credentials] or Authorization: Bearer [token]) in the initial HTTP request.
  • Server Processing: The server receives the request, checks the credentials in the header, validates them, and if successful, processes the request and returns the requested data.
  • Efficiency Gain: If the credentials are valid, the entire transaction is completed in a single round trip between the client and the server.

2. Advantages
  • Reduced Latency and Improved Performance: The primary benefit is eliminating the extra round trip required for the initial challenge and the subsequent authenticated request. This is particularly noticeable in high-latency networks.
  • Fewer Requests: It reduces the total number of HTTP requests and responses by one per resource access, saving bandwidth and server load.

3. Disadvantages
  • Unnecessary Transmission: If the resource ends up not being protected or doesn't require the specific credentials sent, the authentication information (which can be sensitive) was transmitted for no reason.
  • Security Concerns with Basic Auth: If used with Basic Authentication (where credentials are sent in a trivially reversible Base64 format), it makes the credentials more vulnerable if the communication is not encrypted with TLS/SSL (HTTPS), as they are sent even when not strictly needed.
  • Complex Scenarios: It can complicate scenarios involving proxy servers or complex Single Sign-On (SSO) systems where the initial authentication context might change.












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();
    }
}



Code Explanation:

(a) Set the base URI
(b) Sens the API request
(c) Handle Preemptive authentication by code: auth().preemptive().basic("postman", "password")
(d)  get response of the API and validate by equalTo()
(e) Log response on console



Output:

Once the API is successfully authenticated, we will get below response in JSON form.

{
  "authenticated": true
}



Suggested Posts:

1. Test OAuth2 in RestAssured
2. Validate Request and Response by POJO in RestAssured
3. Test Form Authentication in RestAssured
4. Validate Keys in API in RestAssured
5. Validate XML Schema in RestAssured

How to test Basic Authentication by using Rest Assured

 



What is Basic authentication?

Basic authentication is a straightforward, widely supported, and non-interactive method for an API client (like a web browser or mobile app) to provide a user's credentials (typically a username and password) when making an API request. It's one of the simplest authentication schemes built into the HTTP protocol.


More about Basic Authentication

1. The Core Mechanism

Basic authentication works by combining the username and password into a single string, separating them with a single colon, like this: username:password.


2. Encoding

This combined string is then Base64 encoded. Base64 is an encoding scheme, not an encryption method; it is easily reversible and is used primarily to ensure that the credentials can be transmitted across the internet without issues arising from special characters. It does not provide security or confidentiality.


3. The HTTP Header

The resulting Base64-encoded string is then included in the API request within the Authorization HTTP header. The header takes the format:

Authorization:Basic ⟨base64-encoded string⟩

For example, if the username is user and the password is pass, the combined string is user:pass. After Base64 encoding, this might become dXNlcjpwYXNz. The header sent in the request would be:

Authorization:Basic dXNlcjpwYXNz


4. Server-Side Verification

When the API server receives the request, it performs the following steps:

  • It checks for the Authorization header.
  • It verifies that the scheme is Basic.
  • It Base64-decodes the credential string to retrieve the original username:password.
  • It separates the username and password.
  • It attempts to validate these credentials against its user database.

If the credentials are valid, the server processes the API request. If they are invalid, the server typically responds with an HTTP status code of 401 Unauthorized and often includes a WWW-Authenticate header to prompt the client for correct credentials.


To use Basic Authentication in a GET API via Rest Assured, you need to include the username and password using auth().basic(username, password) in your request.









In Basic authentication:

  • The client sends the username and password encoded in Base64 in the request headers.

  • The format is:

Authorization: Basic Base64(username:password)



API to be tested:

https://postman-echo.com/basic-auth
It requires:

Username: postman

Password: password












Maven Dependency:

<dependency>
    <groupId>io.rest-assured</groupId>
    <artifactId>rest-assured</artifactId>
    <version>5.3.0</version>
    <scope>test</scope>
</dependency>



Full Java Code

import io.restassured.RestAssured;
import io.restassured.response.Response;

import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;

public class BasicAuthGetAPI {

    public static void main(String[] args) {
        // Set Base URI
        RestAssured.baseURI = "https://postman-echo.com";

        // Send GET request with basic auth
        Response response = given()
                .auth().basic("postman", "password") // Basic Auth
        .when()
                .get("/basic-auth") // GET Endpoint
        .then()
                .statusCode(200) // Check status code
                .body("authenticated", equalTo(true)) // Validate response body
                .extract().response();

        // Print the response
        System.out.println("Response:\n" + response.prettyPrint());
    }
}



Code Explanation:

(a) Set the bae URI
(b) Send GET request with basic authentication code
(c) Get response and validate with equalTo()
(d) Print the output in console



Output:

Got the response of the GET API in the JSON form as

{
  "authenticated": true
 
}




Suggested Posts:

1. Validate JSON Schema in RestAssured
2. Validate Request and Response by POJO in RestAssured
3. Extract Response by JSONPath in RestAssured
4. Validate Keys in API in RestAssured
5. Validate XML Schema in RestAssured

How to validate API Response from Database in Rest Assured

 



Validating an API Response against the Database in Rest Assured means checking whether the data returned by the API is consistent with the actual data stored in the backend database. This ensures that the API is not only returning the correct structure but also the correct content.

To validate an API response against data in a MySQL database using Rest Assured, follow these steps:








Step-by-Step Guide


Step 1: Setup Project with Required Dependencies


<dependencies>
    <!-- Rest Assured for API Testing -->
    <dependency>
        <groupId>io.rest-assured</groupId>
        <artifactId>rest-assured</artifactId>
        <version>5.3.0</version>
        <scope>test</scope>
    </dependency>

    <!-- MySQL Connector for DB Connection -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.33</version>
    </dependency>

    <!-- JSON handling -->
    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20230227</version>
    </dependency>

    <!-- TestNG (optional for test framework) -->
    <dependency>
        <groupId>org.testng</groupId>
        <artifactId>testng</artifactId>
        <version>7.4.0</version>
        <scope>test</scope>
    </dependency>
</dependencies>


Step 2: MySQL Database Setup

Suppose you have a table users with structure:

CREATE TABLE users (
    id INT PRIMARY KEY,
    email VARCHAR(255),
    first_name VARCHAR(100),
    last_name VARCHAR(100),
    avatar VARCHAR(255)
);



Insert some matching test data from https://reqres.in/api/users?page=2


















Step 3: Java Code

import io.restassured.RestAssured;
import io.restassured.response.Response;

import java.sql.*;
import java.util.List;
import java.util.Map;

import static io.restassured.RestAssured.given;

public class APIDatabaseValidation {

    // JDBC details
    static final String DB_URL = "jdbc:mysql://localhost:3306/testdb";
    static final String USER = "root";
    static final String PASS = "password";

    public static void main(String[] args) throws Exception {
        // Step 1: Get API response
        RestAssured.baseURI = "https://reqres.in";
        Response response = given()
                .when()
                .get("/api/users?page=2")
                .then()
                .statusCode(200)
                .extract().response();

        // Step 2: Extract JSON data from API
        List<Map<String, Object>> apiUsers = response.jsonPath().getList("data");

        // Step 3: Connect to MySQL and validate
        Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
        Statement stmt = conn.createStatement();

        for (Map<String, Object> apiUser : apiUsers) {
            int id = (Integer) apiUser.get("id");
            String email = (String) apiUser.get("email");
            String firstName = (String) apiUser.get("first_name");
            String lastName = (String) apiUser.get("last_name");
            String avatar = (String) apiUser.get("avatar");

            // Query DB for this user
            String query = "SELECT * FROM users WHERE id = " + id;
            ResultSet rs = stmt.executeQuery(query);

            if (rs.next()) {
                assert email.equals(rs.getString("email")) : "Email mismatch for ID " + id;
                assert firstName.equals(rs.getString("first_name")) : "First name mismatch for ID " + id;
                assert lastName.equals(rs.getString("last_name")) : "Last name mismatch for ID " + id;
                assert avatar.equals(rs.getString("avatar")) : "Avatar mismatch for ID " + id;
                System.out.println("User ID " + id + " matched successfully.");
            } else {
                System.err.println("User ID " + id + " not found in database.");
            }
            rs.close();
        }

        // Close DB connection
        stmt.close();
        conn.close();
    }
}


Code explanation: 

(a) Define database details like db username, db password, db url, before main method
(b) In main method, define base URI, send API request and extract data from json response in a map object which is wrapped in a List object.
(c) Create a JDBC connection to the database
(d) Iterate map object by for loop and stored data in string objects
(e) Get data from database using ResultSet object and assert the data with string data that we got from list.
(f) Finally, close the database connection.



Points to Consider
  • Always ensure you are pointing to the same environment (API and DB should be connected to same Test/Stage DB).
  • Handle null values, trimming spaces, and data type mismatches while comparing.
  • Validate not just single records, but also multiple records if the API returns a list.
  • For performance testing, check if the response time of the API aligns with fetching from DB.

Suggested Posts:

1. Validate XML Schema in RestAssured
2. Validate JSON Schema in RestAssured
3. Extract Response by JSONPath in RestAssured
4. Validate Response by Matchers API in RestAssured
5. How to Test SOAP API in RestAssured

How to test a SOAP API by Rest Assured



What is SOAP API?

  • SOAP (Simple Object Access Protocol) is a protocol for exchanging structured data between systems over a network.
  • It uses XML as the message format and typically runs over HTTP/HTTPS.
  • SOAP APIs are often used in enterprise applications (like banking, telecom, insurance) because they enforce strict standards for security, structure, and messaging.

Key Features of SOAP API:
  • Message format → Always XML (not JSON).
  • Transport → Usually HTTP/HTTPS (but can also use SMTP, TCP, etc.).
  • WSDL (Web Services Description Language) → An XML document that describes the service (endpoints, operations, request/response structure).
  • Highly standardized → Supports security (WS-Security), transactions, and reliable messaging.

Testing a SOAP API GET request using Rest Assured is possible but requires understanding how SOAP works. However, SOAP typically uses POST, not GET, because it sends a full XML envelope in the body. But if the SOAP service is exposed via GET (rare, usually for testing or WSDL fetching), we can use RestAssured.get().


How to Test a SOAP API in Rest Assured

When using Rest Assured to test a SOAP API:

1. Understand the WSDL/Endpoint
  • Get the SOAP endpoint URL and know which operations are available.
  • Review the WSDL (it defines the request/response XML structure).
2. Prepare the SOAP Request Body (XML)
  • Create the SOAP envelope (the wrapper XML with <Envelope>, <Header>, and <Body> tags).
  • Add the operation and required parameters inside <Body>.
3. Send the request with Rest Assured
  • Use an HTTP method (usually POST) to send the SOAP envelope as the request body.
  • Set the appropriate headers (like Content-Type: text/xml or application/soap+xml).
4. Receive and parse the SOAP response
  • The server returns a SOAP response envelope in XML.
  • Extract values using XMLPath (similar to JSONPath but for XML).
5. Assertions/Validation
  • Verify status code (e.g., 200 OK).
  • Check that the SOAP response contains expected elements and values.










Key Concepts:

  • SOAP (Simple Object Access Protocol) is a protocol for exchanging structured XML data.

  • WSDL (Web Services Description Language) is used to describe SOAP services.

  • SOAP API is generally tested using POST, but for some services (like fetching WSDL), GET is used.


Example SOAP GET Use Case:

Fetch the WSDL file or perform a test GET to an endpoint.

Let’s use this public SOAP service for currency conversion WSDL (GET example):
http://www.dneonline.com/calculator.asmx?WSDL

This WSDL can be fetched using a GET request.











Step-by-step: Testing SOAP GET using Rest Assured:


Maven Dependency:

<dependency>
    <groupId>io.rest-assured</groupId>
    <artifactId>rest-assured</artifactId>
    <version>5.3.1</version>
    <scope>test</scope>
</dependency>



Java code:

import io.restassured.RestAssured;
import io.restassured.response.Response;

public class SoapGetTest {
    public static void main(String[] args) {
        // Base URI for the SOAP service
        String url = "http://www.dneonline.com/calculator.asmx?WSDL";

        // Send GET request
        Response response = RestAssured
                .given()
                .when()
                .get(url)
                .then()
                .extract()
                .response();

        // Print status code and response
        System.out.println("Status Code: " + response.getStatusCode());
        System.out.println("Content-Type: " + response.getContentType());
        System.out.println("Response Body:\n" + response.getBody().asString());
    }
}


Code explanation:

  • Set the base URI
  • Send GET request
  • Print status code and response on console


We can assert response also by below code.

Optional: Add Test Assertion

import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;

public class SoapGetTest {
    public static void main(String[] args) {
        given()
        .when()
            .get("http://www.dneonline.com/calculator.asmx?WSDL")
        .then()
            .statusCode(200)
            .contentType("text/xml; charset=utf-8")
            .body(containsString("definitions"));
    }
}


Suggested Posts:

1. Validate Keys of API in RestAssured
2. Test Form Authentication in RestAssured
3. Test DELETE API in RestAssured
4. First RestAssured Code to Test API
5. Validate API Response from Database in RestAssured