</>

Technology

Rest Assured

Difficulty

Intermediate

Interview Question

How to handle authentication types in Rest Assured — Basic, Preemptive, Digest, OAuth?

Answer

Authentication in Rest Assured

Rest Assured supports multiple authentication types through the .auth() method chain.

1. Basic Authentication

Java
Response resp = given()
                    .auth()
                    .basic("username", "password")
                    .when()
                    .get("https://reqres.in/api/users/2");

assertEquals(resp.getStatusCode(), 200);

2. Pre-emptive Authentication

Sends credentials with the FIRST request (without waiting for 401 challenge):

Java
Response resp1 = given()
                     .auth()
                     .preemptive()
                     .basic("username", "password")
                     .when()
                     .get("https://reqres.in/api/users/2");

3. Digest Authentication

Digest auth hashes credentials before sending:

Java
Response resp2 = given()
                     .auth()
                     .digest("username", "password")
                     .when()
                     .get("https://reqres.in/api/users/2");

4. OAuth Authentication

Java
Response resp3 = given()
                     .auth()
                     .oauth("consumerKey", "consumerSecret",
                            "accessToken", "secretToken")
                     .when()
                     .get("https://reqres.in/api/users/2");

5. OAuth2 Authentication

Java
Response resp4 = given()
                     .auth()
                     .oauth2("your-access-token")
                     .when()
                     .get("https://reqres.in/api/users/2");

6. Header-Based Authorization (OAuth2)

Java
Response resp5 = given()
                     .header("Authorization", "Bearer your-access-token")
                     .when()
                     .get("https://reqres.in/api/users/2");

Summary

Auth TypeMethodWhen to Use
Basic.auth().basic(u, p)Simple username/password
Preemptive.auth().preemptive().basic(u, p)Avoid round-trip 401 challenge
Digest.auth().digest(u, p)Hashed credentials
OAuth 1.0.auth().oauth(...)Legacy OAuth
OAuth 2.0.auth().oauth2(token)Modern APIs with Bearer tokens

Follow AutomateQA

Related Topics