How to Send Basic Authentication Header in REST-assured

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\": \"\",\n" +
            "  \"password\": \"Passw0rd123!\" \n}";

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

    public void createUser() {
        Response response = given()
                .basic("required_username", "required_password")
                .header("Accept", ContentType.JSON.getAcceptHeader())

        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:

    .basic("required_username", "required_password")