</>

Technology

API Automation

Difficulty

Advanced

Interview Question

How would you test authentication functionality of an API using Rest Assured?

Answer

Scenario: Testing API Authentication

You are tasked with testing the authentication functionality of an API using Rest Assured.

Approach

Step 1: Understand the Auth Mechanism

First, I would ensure that I have clear documentation or understanding of the authentication mechanism — whether it is basic authentication, OAuth, or token-based authentication.

Step 2: Write Test Cases

Happy Path — Valid Credentials:

Java
@Test
public void testLoginWithValidCredentials() {
    String body = "{ \"username\": \"admin\", \"password\": \"admin123\" }";

    Response response = given()
                            .contentType(ContentType.JSON)
                            .body(body)
                            .when()
                            .post("/api/auth/login");

    assertEquals(response.getStatusCode(), 200);
    assertNotNull(response.jsonPath().getString("token"));

    // Save token for subsequent requests
    String token = response.jsonPath().getString("token");
    System.out.println("Token: " + token);
}

Negative Path — Invalid Credentials:

Java
@Test
public void testLoginWithInvalidCredentials() {
    String body = "{ \"username\": \"admin\", \"password\": \"wrongpassword\" }";

    given()
        .contentType(ContentType.JSON)
        .body(body)
        .when()
        .post("/api/auth/login")
        .then()
        .statusCode(401)
        .body("error", equalTo("Invalid credentials"));
}

Missing Token Scenario:

Java
@Test
public void testAccessProtectedRouteWithoutToken() {
    given()
        .when()
        .get("/api/protected/resource")
        .then()
        .statusCode(401)
        .body("message", containsString("token"));
}

Expired Token Scenario:

Java
@Test
public void testWithExpiredToken() {
    String expiredToken = "eyJhbGciOiJIUzI1NiJ9.expired.signature";

    given()
        .header("Authorization", "Bearer " + expiredToken)
        .when()
        .get("/api/users")
        .then()
        .statusCode(401)
        .body("error", equalTo("Token expired"));
}

Step 3: Verify Edge Cases

  • Empty username/password → 400 Bad Request
  • SQL injection in credentials → 400/401 (not 500)
  • Very long password strings → 400
  • Special characters in password → Should work if valid

Test Coverage Matrix

ScenarioExpected Status
Valid credentials200
Wrong password401
Non-existent user401 or 404
Missing auth header401
Expired token401
Malformed token401
Missing required field400

Follow AutomateQA

Related Topics