Authentication of RestAPI test endpoint with basic auth using Rest Assured


Authentication of RestAPI test endpoint with basic auth using Rest Assured

Hi, all welcome to another of my lockdown blog series posts.  In a previous post[1], we looked at how we can use OAuth2 for authorization for accessing secure API endpoints. In this post, we will look at the use of basic auth and how we can pass the user name and password for authentication of the API.

To try out this first create a maven project and add the below dependencies to the pom.xml

<dependencies>
      <dependency>
         <groupId>org.hamcrest</groupId>
         <artifactId>hamcrest-all</artifactId>
         <version>1.3</version>
      </dependency>
      <dependency>
         <groupId>org.hamcrest</groupId>
         <artifactId>hamcrest-junit</artifactId>
         <version>2.0.0.0</version>
      </dependency>
      <dependency>
         <groupId>junit</groupId>
         <artifactId>junit</artifactId>
         <version>4.12</version>
      </dependency>
      <dependency>
         <groupId>com.jayway.restassured</groupId>
         <artifactId>json-schema-validator</artifactId>
         <version>2.8.0</version>
      </dependency>
      <!-- https://mvnrepository.com/artifact/io.rest-assured/rest-assured -->
      <dependency>
         <groupId>io.rest-assured</groupId>
         <artifactId>rest-assured</artifactId>
         <version>4.3.0</version>
         <scope>test</scope>
      </dependency>
      <!-- https://mvnrepository.com/artifact/org.testng/testng -->
      <dependency>
         <groupId>org.testng</groupId>
         <artifactId>testng</artifactId>
         <version>7.1.0</version>
         <scope>test</scope>
      </dependency>
   </dependencies>
 
Once the pom file is updated with the dependencies, the next action is to create a java
class. As shown below we are using auth().basic() to pass the user name and password 
parameters.

package restapitest;

import org.testng.annotations.Test;
import static io.restassured.RestAssured.*;
import io.restassured.http.ContentType;
 
public class BasicAuth {

    @Test
     public void testBaicAuth() {
        given()
            .auth().basic("username-value", "password-value").
                when().
                get("https://your-api.com/basic-auth").
                then().
                assertThat().
                statusCode(200).
                and().
                contentType(ContentType.JSON); 
     }
}


To test this first run the script with invalid user name and passwords, the test should 
fail. Next, run the same test by passing valid authentication URL and see if the assertions
pass and return a status code of 200.
 
[1]invoking-secure-api-endpoint-with-rest

Comments