When you are doing API testing, sometimes the APIs or endpoints are protected. This means you need to be authenticated and authorized to perform certain actions.

There are many ways to protect APIs, but one simple way is to use the Basic Authentication.

In this post, we’ll look at how to send the Basic auth header in REST-assured.

Sending Basic Auth Header in REST-assured

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

import org.junit.Before;
import org.junit.jupiter.api.*;

import static io.restassured.RestAssured.given;

public class UserScenarios {

    private String path;
    private String validRequest = "{\n" +
            "  \"username\": \"some-user\",\n" +
            "  \"email\": \"some-user@email.com\",\n" +
            "  \"password\": \"Passw0rd123!\" \n}";

    @Before
    public void setup() {
        RestAssured.baseURI = "http://localhost:8080";
        path = "/users";
    }

    @Test
    public void createUser() {
        Response response = given()
                .auth()
                .preemptive()
                .basic("required_username", "required_password")
                .header("Accept", ContentType.JSON.getAcceptHeader())
                .contentType(ContentType.JSON)
                .body(validRequest)
                .post(path)
                .then().extract().response();

        Assertions.assertEquals(201, response.getStatusCode());
    }

In some cases, a server might use a challenge-response mechanism to indicate when the user needs to authenticate to access the resource.

By default, REST-assured waits for the server to challenge before sending the credentials and so the library provides the preemptive directive that we can use:

given()
    .auth()
    .preemptive()
    .basic("required_username", "required_password")
#api-testing #rest-assured