Welcome to the final stage of our journey through automated API testing with Kotlin. 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 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 the following code:
Kotlin1import okhttp3.OkHttpClient 2import okhttp3.Request 3import org.junit.jupiter.api.Assertions.assertEquals 4import org.junit.jupiter.api.Test 5 6const val BASE_URL = "http://localhost:8000" 7const val API_KEY = "123e4567-e89b-12d3-a456-426614174000" 8 9class TestAPIKeyAuthentication { 10 11 private val client = OkHttpClient() 12 13 @Test 14 fun TestAPIKey() { 15 // Arrange 16 val request = Request.Builder() 17 .url("$BASE_URL/todos") 18 .addHeader("X-API-Key", API_KEY) 19 .build() 20 21 // Act 22 client.newCall(request).execute().use { response -> 23 // Assert 24 assertEquals(200, response.code) 25 } 26 } 27}
Here, we define a test class TestAPIKeyAuthentication
. Within the test method, we specify the headers, including the X-API-Key
. We use the 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.
We begin our session-based authentication by establishing a fixture 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:
Kotlin1import okhttp3.FormBody 2import okhttp3.OkHttpClient 3import okhttp3.Request 4import okhttp3.Response 5import org.junit.jupiter.api.BeforeEach 6 7const val BASE_URL = "http://localhost:8000" 8 9class TestSessionAuthentication { 10 11 private val client = OkHttpClient() 12 private val authDetails = mapOf( 13 "username" to "testuser", 14 "password" to "testpass123" 15 ) 16 17 fun login(): Response { 18 val formBody = FormBody.Builder() 19 .add("username", authDetails["username"]!!) 20 .add("password", authDetails["password"]!!) 21 .build() 22 23 val request = Request.Builder() 24 .url("$BASE_URL/auth/login") 25 .post(formBody) 26 .build() 27 28 return client.newCall(request).execute() 29 } 30}
The authDetails
map supplies the required credentials, and the login
helper method facilitates independent authentication for each test.
This test leverages the login
helper method to authenticate independently, validating that user credentials create a session successfully:
Kotlin1@Test 2fun test_login() { 3 // Act - Execute the login process using the helper method 4 val loginResponse = login() 5 6 // Assert - Verify that the login was successful 7 assertEquals(200, loginResponse.code) 8}
The use of the helper ensures that this test does not rely on any previous operations, providing isolated verification of login success via status code.
In this test, we independently authenticate using the helper method before confirming that an established session grants access to a protected endpoint:
Kotlin1@Test 2fun test_access_with_session() { 3 // Arrange - Use the login helper method to authenticate 4 val loginResponse = login() 5 val sessionCookie = loginResponse.header("Set-Cookie") ?: "" 6 7 // Act - Request the protected resource using the session 8 val request = Request.Builder() 9 .url("$BASE_URL/todos") 10 .addHeader("Cookie", sessionCookie) 11 .build() 12 13 client.newCall(request).execute().use { response -> 14 // Assert - Confirm access is granted with a successful status code 15 assertEquals(200, response.code) 16 } 17}
The helper method's strategic use ensures that each test individually verifies session-based access, unaffected by the results of prior tests.
By using the login helper method, this test independently authenticates and then verifies the ability to terminate a session, ensuring logout functionality is effective:
Kotlin1@Test 2fun test_logout_with_session() { 3 // Arrange - Use the login helper method to authenticate 4 val loginResponse = login() 5 val sessionCookie = loginResponse.header("Set-Cookie") ?: "" 6 7 // Act - Perform a logout operation to terminate the session 8 val request = Request.Builder() 9 .url("$BASE_URL/auth/logout") 10 .addHeader("Cookie", sessionCookie) 11 .post(FormBody.Builder().build()) // Empty POST body for logout 12 .build() 13 14 client.newCall(request).execute().use { logoutResponse -> 15 // Assert - Verify logout success via status code 16 assertEquals(200, logoutResponse.code) 17 } 18}
This approach confirms isolation, as each session is independently managed, ensuring logout integrity without relying on previous tests.
For JWT-based authentication, we replicate this strategy with a fixture for credentials and a login helper method, enabling each test to independently obtain and manage JWTs:
Kotlin1import okhttp3.OkHttpClient 2import okhttp3.Request 3import okhttp3.FormBody 4import okhttp3.Response 5 6const val BASE_URL = "http://localhost:8000" 7 8class TestJWTAuthentication { 9 10 private val client = OkHttpClient() 11 private val authDetails = mapOf( 12 "username" to "testuser", 13 "password" to "testpass123" 14 ) 15 16 fun login(): Response { 17 val formBody = FormBody.Builder() 18 .add("username", authDetails["username"]!!) 19 .add("password", authDetails["password"]!!) 20 .build() 21 22 val request = Request.Builder() 23 .url("$BASE_URL/auth/login") 24 .post(formBody) 25 .build() 26 27 return client.newCall(request).execute() 28 } 29}
This setup empowers each test to authenticate independently, retrieving tokens without relying on the order or success of other tests.
Using the login
helper method, this test independently verifies that successful authentication results in token issuance, forming the basis for accessing protected resources:
Kotlin1@Test 2fun test_login() { 3 // Act - Authenticate and retrieve JWT tokens 4 val loginResponse = login() 5 6 // Assert - Confirm receipt of tokens and check their existence 7 assertEquals(200, loginResponse.code) 8 9 val responseBody = loginResponse.body?.string() ?: "" 10 val jsonResponse = Json.parseToJsonElement(responseBody).jsonObject 11 12 assertTrue(jsonResponse.containsKey("access_token")) 13 assertTrue(jsonResponse.containsKey("refresh_token")) 14}
By independently logging in, the test ensures token validity regardless of prior tests, establishing the foundation for secure access.
This test independently authenticates using the helper method and verifies that a JWT access token provides entry to a protected endpoint:
Kotlin1@Test 2fun test_access_with_jwt() { 3 // Arrange - Authenticate and obtain an access token using the helper method 4 val loginResponse = login() 5 val responseBody = loginResponse.body?.string() ?: "" 6 val jsonResponse = Json.parseToJsonElement(responseBody).jsonObject 7 val accessToken = jsonResponse["access_token"]?.jsonPrimitive?.content ?: "" 8 9 // Act - Use the access token to request a protected endpoint 10 val request = Request.Builder() 11 .url("$BASE_URL/todos") 12 .addHeader("Authorization", "Bearer $accessToken") 13 .build() 14 15 client.newCall(request).execute().use { response -> 16 // Assert - Confirm the request was successful by checking the status code 17 assertEquals(200, response.code) 18 } 19}
By ensuring the test is independent, this approach validates the token's effectiveness in protecting resources, confirming stateless authentication.
Finally, this test independently authenticates to verify that access and refresh tokens can be invalidated, securing the system against unauthorized reuse:
Kotlin1@Test 2fun test_jwt_logout() { 3 // Arrange - Authenticate and prepare tokens using the helper method 4 val loginResponse = login() 5 val responseBody = loginResponse.body?.string() ?: "" 6 val jsonResponse = Json.parseToJsonElement(responseBody).jsonObject 7 val accessToken = jsonResponse["access_token"]?.jsonPrimitive?.content ?: "" 8 val refreshToken = jsonResponse["refresh_token"]?.jsonPrimitive?.content ?: "" 9 10 // Act - Use access and refresh tokens to process logout 11 val formBody = FormBody.Builder() 12 .add("refresh_token", refreshToken) 13 .build() 14 15 val request = Request.Builder() 16 .url("$BASE_URL/auth/logout") 17 .addHeader("Authorization", "Bearer $accessToken") 18 .post(formBody) 19 .build() 20 21 client.newCall(request).execute().use { logoutResponse -> 22 // Assert - Verify logout success through confirmation of status code 23 assertEquals(200, logoutResponse.code) 24 } 25}
This test confirms the secure handling and invalidation of tokens, ensuring each test independently checks the integrity of the logout process.
Throughout this lesson, we've explored different methods of API authentication: API Keys, Sessions, and JWTs. Each method has distinct ways to test and secure access, and you've seen how to implement tests for them effectively using Kotlin.
When testing any form of authentication, it’s crucial to handle API credentials with care. Avoid hardcoding sensitive information in your codebase, and consider using environment variables or secure vaults in production environments.
As we conclude this lesson and the course, take pride in the journey you've completed. You've gained a comprehensive understanding of how to automate API tests using Kotlin, mastering basic requests through to secure, authenticated endpoints. Continue to practice and explore, applying these skills to ensure robust, reliable APIs in your projects. Congratulations on reaching the end of this course!
