Authentication is the process or action of verifying the identity of a user or process. REST Assured has the capability to test the authentication mechanisms with ease and that is what we are going to see and learn in this tutorial. In this post, we will learn “How to test a Basic Authentication using Rest-Assured”.

 

Let’s understand the authentication a bit, In order to login to an email account, you need to provide a username and password in order to prove your authenticity that whether you are a valid user or not.

There are various types of authentication mechanisms are available like Basic Authentication, API Keys, OAuth. In this particular example, we are going to use the Basic Authentication mechanism.

Simplest example to understand Basic Authentication mechanism using RESTAssured...!!! Share on X

In this tutorial, we are going to cover the below topics:

  1. What is Basic Authentication?
  2. How to make a GET request to the resource that requires Username/Password to authenticate?
  3. How to validate the Response?

 

Let’s begin:

1. What is Basic Authentication?

In this method of authentication, a username and password should be provided by the USER agent to prove their authentication. It’s a straight forward and simple approach which basically uses HTTP header with “username and password” encoded in base64. It does not require cookies, session IDs, etc.

2. How to make a GET request to the resource that requires Username/Password to authenticate?

In order to test this feature, I’ve built a sample REST service using Spring boot. You can simply click on this link and import this Github repository on your local machine and run it as a spring boot application.

Note: This project is a Spring Boot web application. So, if you are using Eclipse then install the required spring boot support from the Eclipse Marketplace or if it’s possible then download ‘STS’ (Spring Tool Suite). STS is a flavor of Eclipse inbuilt with Spring Boot support. 

A brief description of the web service that we are going to test:

This service is holding the agent’s information like agentno, agentname etc. and it is available on this URI: http://localhost:8006/agents . But in order to get that, first, we need to authenticate with valid credentials (Username & Password)

1. Request Endpoint: GET

2. Authentication Information :

Valid Username: isha

Valid Password: durani

3. Service Endpoint URL: ‘http://localhost:8006/agents’

4. Expected Response :

{  
   "agentNo":"1",
   "agentName":"Yashika",
   "agentSsn":"123-12-1452"
},
{  
   "agentNo":"2",
   "agentName":"Yogi",
   "agentSsn":"541-58-8596"
},
{  
   "agentNo":"3",
   "agentName":"Yash",
   "agentSsn":"457-54-5877"
},
{  
   "agentNo":"4",
   "agentName":"Isha",
   "agentSsn":"123-45-7489"
},
{  
   "agentNo":"5",
   "agentName":"Gaurangee",
   "agentSsn":"666-95-8877"
},
{  
   "agentNo":"6",
   "agentName":"Deepak",
   "agentSsn":"325-55-4422"
}

 

Now, let’s look at the Java code to perform basic authentication using rest assured:

import static io.restassured.RestAssured.given;

import org.testng.annotations.Test;

import io.restassured.RestAssured;
import io.restassured.response.Response;

public class BasicAuthenticationTest {

    @Test
    public void basicAuthenticationTest() {

        RestAssured.baseURI = "http://localhost:8006";

        Response response = null;

        String invalidusername = "deepak";
        String invalidpassword = "";

        String validusername = "isha";
        String validpassword = "durani";


        //Scenario with incorrect username & password
        response = given()
            .auth().basic(invalidusername, invalidpassword)
            .when()
            .get("/agents");

        System.out.println("Access Unauthorized \nStatus Code :" + response.getStatusCode());
        System.out.println("Response :" + response.asString());

        System.out.println("\n---------------------------------------------------\n");

        //Scenario with correct username & password	
        response = given()
            .auth().basic(validusername, validpassword)
            .when()
            .get("/agents");

        System.out.println("Access Authorized \nStatus Code :" + response.getStatusCode());
        System.out.println("Response :" + response.asString());
    }

}

 

Let’s try to understand the code:

1. Setting up Base URI

RestAssured.baseURI = "http://localhost:8006";

Base URI is the root address of the Resource. And, by this particular line of code, we are specifying to REST assured to use “http://localhost:8006” as the root URL of the service.

2. Specifying the exact resource to look for and make a GET request to that resource with username and password

Response response = null;
		
		String validusername = "isha";
		String validpassword = "durani";

		response = given()
				.auth().basic(validusername,validpassword)
				.when()
				.get("/agents");

 

Here, using this code, we are looking to make a GET request to an exact resource which is “/agents” in this case. Hence, the complete Service Endpoint would be “http://localhost:8006/agents” to which we are sending a GET request with username and password. The output of the POST call will be stored in the REST Assured ‘Response’ object.

3. Response validation

//For unsuccessful scenario
System.out.println("Access Unauthorized \nStatus Code :" + response.getStatusCode());
System.out.println("Response :" + response.asString());

//For successful scenario
System.out.println("Access Authorized \nStatus Code :" + response.getStatusCode());
System.out.println("Response :" + response.asString());

a. response.asString() : It displays the response in a string format

b. response.getStatusCode() : This line of code would extract the status code from the response.

3. How to validate the Response?

I’ve already explained the validation above. Now, Let’s just execute the above Test class (BasicAuthenticationTest) in eclipse and verify the output.

Eclipse Console Output:

[RemoteTestNG] detected TestNG version 6.14.3
Access Unauthorized 
Status Code :401
Response :

---------------------------------------------------

Access Authorized 
Status Code :200
Response :[{"agentNo":"1","agentName":"Yashika","agentSsn":"123-12-1452"},{"agentNo":"2","agentName":"Yogi","agentSsn":"541-58-8596"},{"agentNo":"3","agentName":"Yash","agentSsn":"457-54-5877"},{"agentNo":"4","agentName":"Isha","agentSsn":"123-45-7489"},{"agentNo":"5","agentName":"Gaurangee","agentSsn":"666-95-8877"},{"agentNo":"6","agentName":"Deepak","agentSsn":"325-55-4422"}]
PASSED: basicAuthenticationTest

===============================================
    Default test
    Tests run: 1, Failures: 0, Skips: 0
===============================================


===============================================
Default suite
Total tests run: 1, Failures: 0, Skips: 0
===============================================

 

That’s it, it’s that simple to perform Basic Authentication using REST Assured API: ?

Simplest example to understand Basic Authentication mechanism using RESTAssured...!!! Share on X

 

If you like this post, please click like button and share it with others on Twitter. Also, check out my other useful blog posts on Rest Assured:

Other Useful References:

Author

  • Deepak Verma

    Deepak Verma is a Test Automation Consultant and Software development Engineer for more than 10 years. His mission is to help you become an In-demand full stack automation tester.

    He is also the founder of Techndeck, a blog and online coaching platform dedicated to helping you succeed with all the automation basics to advanced testing automation tricks.

    View all posts