Last Updated On
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. REST assured supports several authentication schemes, for example OAuth, digest, certificate, form and preemptive basic authentication.
In this post, we’ll look at how to send the authentication credentials (username, password) in REST Assured.
Add the below-mentioned dependencies to the Maven project.
<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>
Sending Basic Auth Header in REST Assured
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);
}
}
Below is an example of authentication in Postman.
![](https://qaautomation.expert/wp-content/uploads/2024/01/image-189.png?w=1200)
Let us create the test for the above example using Rest Assured.
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);
}
The output of the above program is
![](https://qaautomation.expert/wp-content/uploads/2024/01/image-188.png?w=1200)
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("username", "password")
Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!! Cheers!!