Basic Authentication using RestAssured

Carvia Tech | July 10, 2019 | | 31 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. SDET: JUnit interview questions for automation engineer
  3. OAuth2 protected resources in RestAssured Testcases
  4. File upload in RestAssured
  5. Commonly used Http methods in RESTful services
  6. SDET: Rest Assured Interview Questions
  7. OAuth2 protected resources using RestTemplate



Find more on this topic:
SDET Interviews image
SDET Interviews

SDET Java Interview pattern and collection of questions covering SDET coding challenges, automation testing concepts, functional, api, integration, performance and security testing, junit5, testng, jmeter, selenium and rest assured

Last updated 1 week ago


Recommended books for interview preparation:

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