How to send basic authentication credentials in Rest Assured

HOME

 <dependencies>

       <!-- Rest Assured Dependency -->
      <dependency>
         <groupId>io.rest-assured</groupId>
        <artifactId>rest-assured</artifactId>
        <version>5.3.2</version>
        <scope>test</scope>
      </dependency>

        <!-- TestNG Dependency-->
      <dependency>
          <groupId>org.testng</groupId>
         <artifactId>testng</artifactId>
         <version>7.8.0</version>
         <scope>test</scope>
       </dependency>

</dependencies>

import io.restassured.http.ContentType;
import io.restassured.response.Response;
import org.testng.Assert;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;

public class BasicAuth_Demo {

   private String validRequest = "{" +
           "\"username\": \"Samu01\"," +
           "\"email\": \"samuel@email.com\"," +
           "\"password\": \"Passw0rd123!\"" +
           "}";

    @Test
    public void createUser() {
        Response response = given()
                .auth()
                .preemptive()
                .basic("username", "password")
                .header("Accept", "application/json")
                .contentType(ContentType.JSON)
                .body(validRequest)
                .when()
                .post("http://localhost:8080/users")
                .then()
                .extract()
                .response();

        int statusCode = response.getStatusCode();

        Assert.assertEquals(statusCode,200);
    }
}

import io.restassured.http.ContentType;
import io.restassured.response.Response;
import org.junit.Assert;
import org.junit.Test;

import static io.restassured.RestAssured.given;

public class BasicAuth_Demo {

    @Test
    public void validateCredentials() {

        Response response = given()
                .auth()
                .preemptive()
                .basic("user", "pass")
                .header("Accept", "application/json")
                .contentType(ContentType.JSON)
                .when()
                .get("https://httpbin.org/basic-auth/user/pass")
                .then()
                .log().all()
                .extract()
                .response();

        int statusCode = response.getStatusCode();

        Assert.assertEquals(200,statusCode);
    }

given()
    .auth()
    .preemptive()
    .basic("username", "password")

Leave a comment