Rest Assured Authentication

Let’s analyze how we can authenticate with REST Assured to test and validate a secured API properly.

The various authentication supports available are:

  1. Basic Authentication
  2. Preemptive Authentication
  3. Digest Authentication
  4. Form Authentication

Let’s look at each of them in detail one by one


Basic Authentication:

A REST request has a special header called Authorization Header, which contains the credentials id and password. It requires the user to send user id and a password encoded in Base64 with the request. The request sent with authorization header is further validated by the server including the credentials which authorize the access of the private sources. The credentials can be configured easily using Rest Assured as below:

given().auth()
.basic("user1", "user123")
.when()
.get("https://petstore.swagger.io/v2/pet/GetAllPets")
.then()
.assertThat()
.statusCode(200);

 

Preemptive Authentication:

HTTP provides a simple challenge-response authentication mechanism that may be used by a server to challenge a client request and by a client to provide authentication information. By default, REST Assured waits for the server to challenge before sending the credentials. This creates inconvenience in some cases like when the server is configured to retrieve a login form instead of the challenge-response. Thus, in this case, Preemptive Authentication is used:

 .preemptive()
.basic("user1", "user123")
.when()
//…

 

Digest Authentication:

This is also considered a “weak” authentication method. In this type, the user request is received by a network server which is then sent to a domain controller. The domain controller sends a special key, called a digest session key, to the server that received the original request. The user should produce a response (which is encrypted and transmitted to the server), is of the correct form then the server grants the user access to the network. 

given().auth()
.digest("user1", "user123")
.when()
//…

 

Form Authentication:

Many services provide an HTML form for the user to authenticate by filling in the fields with their credentials. When the user submits the form, the browser executes a POST request with the information and each input field corresponds with a form parameter sent in the request.

given().auth()
.form("user1","user123",
new FormAuthConfig("/perform_login", "USER", "PASS123"))
//….