Testing Authenticated API Endpoints

Testing Authenticated Endpoints

Welcome to the last stop of our journey through automated API testing with Ruby. In this lesson, we'll focus on testing authenticated API endpoints. While you've already learned to organize tests and handle CRUD operations using RSpec, 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 Ruby's Net::HTTP:

require 'rspec'
require 'net/http'
require 'uri'

BASE_URL = "http://localhost:8000"
API_KEY = "123e4567-e89b-12d3-a456-426614174000"

RSpec.describe 'API Key Authentication' do
  it 'authenticates using API Key' do
    # Arrange
    uri = URI("#{BASE_URL}/todos")
    request = Net::HTTP::Get.new(uri)
    request['X-API-Key'] = API_KEY

    # Act
    response = Net::HTTP.start(uri.hostname, uri.port) do |http|
      http.request(request)
    end

    # Assert
    expect(response.code.to_i).to eq(200)
  end
end

Here, we define an RSpec test block for API Key Authentication. Within the test, we specify the headers, including the X-API-Key. We use Net::HTTP 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 let block 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:

require 'rspec'
require 'net/http'
require 'uri'
require 'json'

BASE_URL = "http://localhost:8000"

RSpec.describe 'Session Authentication' do
  let(:auth_details) do
    # Arrange - Providing user credentials
    { username: 'testuser', password: 'testpass123' }
  end

  # Helper method for sending a login POST request
  def login(session, auth_details)
    uri = URI("#{BASE_URL}/auth/login")
    request = Net::HTTP::Post.new(uri)
    request.content_type = 'application/json'
    request.body = auth_details.to_json
    session.request(request)
  end

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

Since JWT authentication is stateless, the server does not maintain session data. This means the access token itself must carry all the necessary authentication information, and must be included with each request. Unlike session authentication, simply reusing a connection won’t help unless the token is explicitly included in headers.

Session Authentication: Testing Login

This test leverages the login helper method to authenticate independently, validating that user credentials create a session successfully:

  it 'logs in successfully' do
    # Arrange - Initialize session
    session = Net::HTTP.new(URI(BASE_URL).hostname, URI(BASE_URL).port)

    # Act - Execute the login process using the helper method
    login_response = login(session, auth_details)

    # Assert - Verify that the login was successful
    expect(login_response.code.to_i).to eq(200)
  end

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.

Session Authentication: Testing Protected Endpoint

In this test, we independently authenticate using the helper method before confirming that an established session grants access to a protected endpoint:

  it 'accesses protected endpoint with session' do
    # Arrange - Use the login helper method to authenticate
    session = Net::HTTP.new(URI(BASE_URL).hostname, URI(BASE_URL).port)
    login(session, auth_details)

    # Act - Request the protected resource using the session
    uri = URI("#{BASE_URL}/todos")
    request = Net::HTTP::Get.new(uri)
    response = session.request(request)

    # Assert - Confirm access is granted with a successful status code
    expect(response.code.to_i).to eq(200)
  end

The helper method's strategic use ensures that each test individually verifies session-based access, unaffected by the results of prior tests.

Session Authentication: Testing Logout

By using the login helper method, this test independently authenticates and then verifies the ability to terminate a session, ensuring logout functionality is effective:

  it 'logs out successfully' do
    # Arrange - Use the login helper method to authenticate
    session = Net::HTTP.new(URI(BASE_URL).hostname, URI(BASE_URL).port)
    login(session, auth_details)

    # Act - Perform a logout operation to terminate the session
    uri = URI("#{BASE_URL}/auth/logout")
    request = Net::HTTP::Post.new(uri)
    logout_response = session.request(request)

    # Assert - Verify logout success via status code
    expect(logout_response.code.to_i).to eq(200)
  end
end

This approach confirms isolation, as each session is independently managed, ensuring logout integrity without relying on previous tests.

JWT Authentication: Setup

For JWT-based authentication, we replicate this strategy with a let block for credentials and a login helper method, enabling each test to independently obtain and manage JWTs:

RSpec.describe 'JWT Authentication' do
  let(:auth_details) do
    # Arrange - User credentials for JWT
    { username: 'testuser', password: 'testpass123' }
  end

  # Helper method for sending a login POST request
  def login(auth_details)
    uri = URI("#{BASE_URL}/auth/login")
    request = Net::HTTP::Post.new(uri)
    request.content_type = 'application/json'
    request.body = auth_details.to_json
    Net::HTTP.start(uri.hostname, uri.port) do |http|
      http.request(request)
    end
  end

This setup empowers each test to authenticate independently, retrieving tokens without relying on the order or success of other tests.

JWT Authentication: Testing Login

Using the login helper method, this test independently verifies that successful authentication results in token issuance, forming the basis for accessing protected resources:

  it 'logs in and receives JWT tokens' do
    # Act - Authenticate and retrieve JWT tokens
    login_response = login(auth_details)

    # Assert - Confirm receipt of tokens and check their existence
    expect(login_response.code.to_i).to eq(200)
    tokens = JSON.parse(login_response.body)
    expect(tokens).to have_key('access_token')
    expect(tokens).to have_key('refresh_token')
  end

By independently logging in, the test ensures token validity regardless of prior tests, establishing the foundation for secure access.

JWT Authentication: Testing Protected Endpoint

This test independently authenticates using the helper method and verifies that a JWT access token provides entry to a protected endpoint:

  it 'accesses protected endpoint with JWT' do
    # Arrange - Authenticate and obtain an access token using the helper method
    login_response = login(auth_details)
    access_token = JSON.parse(login_response.body)['access_token']

    # Act - Use the access token to request a protected endpoint
    uri = URI("#{BASE_URL}/todos")
    request = Net::HTTP::Get.new(uri)
    request['Authorization'] = "Bearer #{access_token}"
    response = Net::HTTP.start(uri.hostname, uri.port) do |http|
      http.request(request)
    end

    # Assert - Confirm the request was successful by checking the status code
    expect(response.code.to_i).to eq(200)
  end

By ensuring the test is independent, this approach validates the token's effectiveness in protecting resources, confirming stateless authentication.

JWT Authentication: Testing Logout

Finally, this test independently authenticates to verify that access and refresh tokens can be invalidated, securing the system against unauthorized reuse:

  it 'logs out and invalidates JWT tokens' do
    # Arrange - Authenticate and prepare tokens using the helper method
    login_response = login(auth_details)
    access_token = JSON.parse(login_response.body)['access_token']
    refresh_token = JSON.parse(login_response.body)['refresh_token']

    uri = URI("#{BASE_URL}/auth/logout")
    request = Net::HTTP::Post.new(uri)
    request['Authorization'] = "Bearer #{access_token}"
    request.content_type = 'application/json'
    request.body = { refresh_token: refresh_token }.to_json

    # Act - Use access and refresh tokens to process logout
    logout_response = Net::HTTP.start(uri.hostname, uri.port) do |http|
      http.request(request)
    end

    # Assert - Verify logout success through confirmation of status code
    expect(logout_response.code.to_i).to eq(200)
  end
end

This test confirms the secure handling and invalidation of tokens, ensuring each test independently checks the integrity of the logout process.

Summary and Practices

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 Ruby and RSpec.

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 Ruby, 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!

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