Testing Authenticated Endpoints with Java, HttpClient, Gson, and JUnit

Testing Authenticated Endpoints

Welcome to the final lesson of our journey through automated API testing with Java. In this lesson, we'll focus on testing authenticated API endpoints. While you've already learned to organize tests and handle CRUD operations using JUnit, today we'll delve into how APIs manage secure access through different authentication methods — API Keys, Sessions, and JWT (JSON Web Tokens).

Authentication is crucial for securing API endpoints against unauthorized access. By understanding how to test these mechanisms, you'll ensure that your API maintains its integrity and protects sensitive data. We'll explore practical examples for each authentication method, giving you the tools to verify that only authorized users can interact with protected resources.

API Key Authentication

API Key authentication is one of the simplest ways to secure an API. It involves sending a unique key as part of the request headers, allowing access to protected endpoints. Let's look at an example of how you can set up and test API Key authentication using Java's HttpClient and JUnit:

public class TestAPIKeyAuthentication {
    private static final String BASE_URL = "http://localhost:8000";
    private static final String API_KEY = "123e4567-e89b-12d3-a456-426614174000";

    @Test
    public void testAPIKeyAuthentication() throws Exception {
        // Arrange
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(new URI(BASE_URL + "/todos"))
                .header("X-API-Key", API_KEY)
                .GET()
                .build();

        // Act
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

        // Assert
        assertEquals(200, response.statusCode());
    }
}

Here, we define a test class TestAPIKeyAuthentication. Within the test method, testAPIKeyAuthentication, we specify the headers, including the X-API-Key. We use Java's HttpClient to make a call to the /todos endpoint and pass the headers, ensuring the API key is included in the request. The test then asserts that the response status code is 200, indicating successful authentication and access to the endpoint.

Session Authentication: Setup

We begin our session-based authentication by establishing a method for user credentials and a helper method for login. This enables each test to authenticate independently, providing a consistent environment to test both login functionality and access to protected endpoints:

public class TestSessionAuthentication {
    private static final String BASE_URL = "http://localhost:8000";
    private static final Gson gson = new Gson();

    private Map<String, String> getAuthDetails() {
        // Arrange - Providing user credentials
        Map<String, String> authDetails = new HashMap<>();
        authDetails.put("username", "testuser");
        authDetails.put("password", "testpass123");
        return authDetails;
    }

    // Helper method for sending a login POST request
    public HttpResponse<String> login(HttpClient client, Map<String, String> authDetails) throws Exception {
        String requestBody = gson.toJson(authDetails);
        HttpRequest request = HttpRequest.newBuilder()
                .uri(new URI(BASE_URL + "/auth/login"))
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(requestBody))
                .build();
        return client.send(request, HttpResponse.BodyHandlers.ofString());
    }
}

The getAuthDetails method supplies the required credentials, and the login helper method facilitates independent authentication for each test.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal