Showing posts with label Automated API Testing. Show all posts
Showing posts with label Automated API Testing. Show all posts

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 test Form Authentication by using rest Assured

 



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.
This is different from Basic/Digest authentication, where credentials are passed in HTTP headers.
Form-based login is very common in web applications.


How to test Form Authentication using Rest Assured
When testing Form Authentication in Rest Assured, the process usually looks like this:

1. Provide login credentials

  • Supply the username and password that the login form requires.

2. Tell Rest Assured the login form details
  • Specify the login page (form action URL), and the parameter names for username and password fields (e.g., username, password).

3. Send login request
  • 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.

5. Access protected resources
  • 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 usernamepassword)
  • Then it stores session/cookie for further requests like GETPOST, etc.

Sample API for Form Auth

We will use: https://the-internet.herokuapp.com/login (a public test site)

  • Login URLhttps://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
    }
}


Code explanation:

(a) Create session filter and maintain session across requests
(b) Login using form based authentication
(c) Access GET API after login
(d) Print the response on console


Maven Dependencies

<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