Middleware

API Key Middleware

Introduction

The API Key middleware provides a lightweight, static API key authentication mechanism. It is ideal for service-to-service communication or simple API protection where OAuth or JWT complexity is not required.

Key features include:

  • Flexible Extraction: Can retrieve API keys from HTTP headers or URL query parameters.
  • High Performance: Uses associative array lookups for O(1) key validation speed.
  • CORS Support: Built-in handling to allow OPTIONS preflight requests.
  • Path Whitelisting: Easily exclude specific public routes (e.g., health checks).

Installation

Install the middleware via composer by running:

composer require kipchak/middleware-auth-key

Configuration

The configuration in auth.key.php can be used to configure this middleware.

Global Settings

  • enabled (bool): Master switch. Set to true to enforce API key checks globally.
  • header (string): The name of the HTTP header to inspect.
    • Default: 'apikey'
  • query_param (string): The name of the URL query parameter to inspect.
    • Default: 'apikey'

Authorised Keys

  • authorised_keys (array): An associative array of valid API keys.
    • Format: ['actual_api_key_secret' => 'client_identifier']
  • Note: The middleware checks if the provided key exists as a key in this array. This structure is used for performance reasons (hash map lookup).
'authorised_keys' => [
    'secret-key-123' => 'mobile-app',
    'secret-key-456' => 'billing-service',
],

Request Handling

  • ignore_options (bool): If true, OPTIONS requests (used for CORS preflight checks) are allowed without a key.
  • ignore_paths (array): A list of URI paths that should be publicly accessible.
    • Default: ['/status']

Usage

Once enabled, the middleware checks incoming requests for the configured credentials. The middleware checks the header first, and if not found, checks the query parameter.

1. Authentication via Header

By default, the middleware looks for the apikey header.

    GET /api/resource HTTP/1.1
    Host: example.com
    apikey: secret-key-123

2. Authentication via Query Parameter

Alternatively, clients can pass the key in the URL (useful for webhooks or simple GET requests).

    GET /api/resource?apikey=secret-key-123 HTTP/1.1
    Host: example.com

Customizing Key Names

If you want to use standard headers like X-API-Key, update your configuration:

    'header' => 'X-API-Key',
    'query_param' => 'key',

Now the request would look like:

    GET /api/resource HTTP/1.1
    Host: example.com
    X-API-Key: secret-key-123

Git Repository

The source code for this driver is available on 1x.ax at https://1x.ax/mamluk/kipchak/middlewares/auth-key.

Previous
Auth - OAuth 2 (JWKS)