Basic Authentication using RestAssured

Carvia Tech | July 10, 2019 | | 10 views


In this article we will explore how to access Basic Auth protected resource from Rest Assured testcase, with a coding sample.

Lets say you have a REST endpoint that requires basic auth.

Request Body
{
	"wp_user_id": "as81hudh87hg8",
	"name": "Foo"
}
Response
{
    "data": "uuid",
    "success": true,
    "errorCode": 0
}

Let’s further assume that username and password for accessing this resource are: wbc_test_user/ZiUN3NB12h

We can write the below TestCase in RestAssured that will make a post call on the Basic Auth protected resource.

BasicAuthTest.java
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 {

    private final Logger logger = LoggerFactory.getLogger(OAuth2Test.class);

    @Test
    public void basicAuthLogin() {
        String username = "wbc_test_user";
        String password = "ZiUN3NB12h";

        //language=JSON
        String jsonBody = "{\n" +
                "  \"wp_user_id\": \"as81hudh87hg8\",\n" +
                "  \"name\": \"Foo\"\n" +
                "}";

        given().auth().preemptive().basic(username, password)
                .body(jsonBody)
                .contentType(ContentType.JSON)
                .when()
                .post("http://localhost:8080/api/client")
                .then()
                .body("success", equalTo(true));
    }
}

Top articles in this category:
  1. Top 50 SDET Java Programming Interview Questions & Answers
  2. File upload in RestAssured
  3. Commonly used Http methods in RESTful services
  4. OAuth2 protected resources in Rest Assured Testcases
  5. OAuth2 protected resources using RestTemplate
  6. How to reverse a number in Java
  7. How will you compare two java objects



Find more on this topic:
SDET Interviews image
SDET Interviews

End to end automation testing using Selenium Web Driver, Rest Assured, JMeter, Junit, TestNG etc.

Last updated 1 month ago


Recommended books for interview preparation:

This website uses cookies to ensure you get the best experience on our website. more info