$ ./gradlew :bootRun
REST Assured Basic Authentication
Upasana | December 30, 2019 | 2 min read | 5,648 views | Rest Assured
In this article we will explore how to develop Rest Assured testcase for Basic Auth protected resource, with a coding sample.
Setting up Basic Auth Server
Creating the basic auth server is outside the scope for this tutorial, you can just clone this project and run it from command line.
Now we should have the following endpoint running on the server:
{
"name": "Foo"
}
{
"data": "hello Foo",
"success": true
}
Let’s further assume that username and password for accessing this resource are: admin/password
Rest Assured Basic Auth Testcase
We will develop the below RestAssured testcase that will make a post call on the Basic Auth protected resource and assert the behaviour.
import io.restassured.http.ContentType;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static io.restassured.RestAssured.given;
import static org.hamcrest.core.IsEqual.equalTo;
public class BasicAuthTest {
@Test
public void basicAuthLogin() {
String username = "admin";
String password = "password";
//language=JSON
String jsonBody = "{\n" +
" \"name\": \"Foo\"\n" +
"}";
given().auth().preemptive().basic(username, password)
.body(jsonBody)
.contentType(ContentType.JSON)
.when()
.post("http://localhost:8080/secured/hello")
.then()
.statusCode(200) (1)
.body("success", equalTo(true)) (2)
.body("data", equalTo("hello Foo"));
}
}
1 | Asserting the HTTP response status code |
2 | Asserting the json content |
Preemptive vs Challenged Basic Authentication
There are two types of basic authentications - preemptive and "challenged basic authentication".
Preemptive basic authentication sends the credentials even before the server ives an unauthorized response in certain situations, thus additional call is avoided. We normally prefer Preemptive basic authentication in most situations, unless we want to test the server’s ability to send back the challenge response.
When using challenged basic authentication REST Assured will not supply the credentials unless the server has explicitly asked for it. This means that REST Assured will make an additional request to the server in order to be challenged and then follow up with the same request once more but this time setting the basic credentials in the header.
Rest Assured:
- Rest Assured API Testing Interview Questions
- RestAssured multipart file upload
- OAuth2 protected resources in RestAssured Testcases
Top articles in this category:
- Rest Assured API Testing Interview Questions
- Java 11 HttpClient with Basic Authentication
- REST Assured with plain/text response body
- RestAssured multipart file upload
- 50 Java Interview Questions for SDET Automation Engineer
- REST Assured vs Apache HttpClient and RestTemplate
- OAuth2 protected resources in RestAssured Testcases