Showing posts with label Rest Assured Examples. Show all posts
Showing posts with label Rest Assured Examples. 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 Keys in API in Rest Assured

 



To validate that a JSON response body contains a specific key using hasKey() from Hamcrest Matchers in Rest Assured, 

follow this step-by-step guide using the endpoint:


1. Send API Request

  • Use Rest Assured to send an HTTP request (GET, POST, etc.) to the API endpoint.
  • Capture the response in a Response object

2. Extract JSON Response

  • Convert the response body into a JSON object using Rest Assured’s inbuilt methods.
  • This allows easy access to keys and values.

3. Check for Key Existence
  • Extract the JSON as a map or use JSONPath.
  • Validate whether specific keys are present in the response.
  • Example: If response has { "id": 101, "name": "Alex" }, you should check whether keys id and name exist.

4. Assertion for Keys
  • Use assertions (assertThat, containsKey, hasKey) to ensure that expected keys exist in the response.
  • This guarantees that the API contract is maintained.

5. Validate Nested Keys
  • For JSON objects with nested structures, you can use dot notation in JSONPath to check sub-keys.
  • Example: "address.city" should exist inside "address".

6. Schema Validation (Optional)
  • Instead of validating keys one by one, you can use a JSON Schema file.
  • Schema validation ensures all required keys are present with correct data types.









URL: https://reqres.in/api/users?page=2






Goal: Validate that the JSON response has a key like "page""data", etc.


Code Example in Java (Rest Assured + Hamcrest hasKey())

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

public class HasKeyExample {
    public static void main(String[] args) {
        RestAssured.baseURI = "https://reqres.in";

        given()
        .when()
            .get("/api/users?page=2")
        .then()
            .statusCode(200)
            .body("$", hasKey("page"))          // top-level key
            .body("$", hasKey("per_page"))      // another top-level key
            .body("$", hasKey("data"))          // array of users
            .body("support", hasKey("url"))     // nested key inside "support"
            .body("support", hasKey("text"));   // another nested key
    }
}




Code explanation: 

(a) In main method, set base URI
(b) Send request to api and get response.
(c) In response body, we have to use hasKey() to validate Json keys as shown in the code.


Explanation:

  • "$" refers to the root of the JSON response.
  • hasKey("keyName") checks if a key exists at that JSON level.
  • body("support", hasKey("url")) checks if the support object has a url key.



Sample Response from https://reqres.in/api/users?page=2

Below is the json resposne of the API, having json elements like key-value pairs of page,per_page,total,etc.

{
    "page": 2,
    "per_page": 6,
    "total": 12,
    "total_pages": 2,
    "data": [...],
    "support": {
        "url": "https://reqres.in/#support-heading",
        "text": "To keep ReqRes free, contributions towards server costs are appreciated!"
    }
}



Maven Dependencies

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


Suggested Posts:

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

How to extract Response in Rest Assured by JSONPath

  



What is JsonPath?

  • JSONPath is a query language (similar to XPath for XML) that allows you to navigate through a JSON response and extract specific values.
  • It helps testers pick out individual fields, nested objects, or arrays from a JSON response without having to parse the entire response manually.
Example JSON response:

{
  "user": {
    "id": 101,
    "name": "Himanshu",
    "roles": ["admin", "editor"]
  }
}


With JSONPath you could extract:

user.id → returns 101
user.name → returns "Himanshu"
user.roles[0] → returns "admin"








How to extract Response in Rest Assured by JSONPath

When you send a request with Rest Assured and get back a response:

1. Capture the response

  • First, the API response is stored in a variable.
2. Use JSONPath to extract fields
  • Apply JSONPath expressions (like data.id, user.name, etc.) on the response to extract specific values.
3. Assertions or Reuse
  • Once extracted, the values can be: Verified against expected values (assertions), Reused in subsequent requests (chaining).

Example in words:
  • If the response contains "id": 101, you can use JSONPath expression "id" to extract it.
  • If the response contains a nested object like "user.name", you can use that path to fetch the value.
  • If the response contains an array, you can specify the index, like "roles[1]" to fetch "editor".

URL:

https://reqres.in/api/users?page=2


Below is the screenshot of response of API: https://reqres.in/api/users?page=2

















Sample Java Code using Rest Assured:

import io.restassured.RestAssured;
import io.restassured.response.Response;
import io.restassured.path.json.JsonPath;

import java.util.List;

public class JsonPathExample {

    public static void main(String[] args) {

        // Step 1: Set Base URI
        RestAssured.baseURI = "https://reqres.in";

        // Step 2: Send GET request and get response
        Response response = RestAssured
                .given()
                .when()
                .get("/api/users?page=2")
                .then()
                .statusCode(200)
                .extract()
                .response();

        // Step 3: Parse response with JsonPath
        JsonPath jsonPath = response.jsonPath();

        // Step 4: Extract specific values
        int total = jsonPath.getInt("total");
        int perPage = jsonPath.getInt("per_page");
        String firstEmail = jsonPath.getString("data[0].email");
        List<String> allEmails = jsonPath.getList("data.email");

        // Step 5: Print the extracted values
        System.out.println("Total users: " + total);
        System.out.println("Users per page: " + perPage);
        System.out.println("First user's email: " + firstEmail);
        System.out.println("All emails:");
        for (String email : allEmails) {
            System.out.println(email);
        }
    }
}


Code explanation:

(a) Set base URI
(b) Send request and get response from server
(c) parse response with JsonPath
(d) Extract specific values
(e) Print the extracted values



Common JsonPath Queries:

TaskJsonPath Expression
Total number of usersjsonPath.getInt("total")
Email of first userjsonPath.getString("data[0].email")
List of all emailsjsonPath.getList("data.email")
ID of last userjsonPath.getInt("data[-1].id")




Maven Dependencies:

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


Suggested Posts:

1. Test Form Authentication in RestAssured
2. Test Digesh Auth in RestAssured
3. Test DELETE API in RestAssured
4. First RestAssured Code to Test API
5. How to Test Basic Authentication in RestAssured