Skip to main content

Overview

The keyauth middleware provides API key authentication. It validates API keys from headers, query parameters, or cookies. Perfect for machine-to-machine authentication and public APIs. Use it when you need:
  • API key authentication
  • Service-to-service authentication
  • Third-party API access control
  • Simple API protection without user sessions

Installation

Quick Start

Configuration

Options

KeyLookup Format

The KeyLookup option uses the format "source:name":

Examples

Static API Keys

Database Lookup

Query Parameter

Multiple Lookup Sources

With Auth Scheme

Custom Error Handler

Access API Key in Handler

Rate Limiting Per Key

API Reference

Functions

Extracting Key

Types

Error Types

Technical Details

Implementation Overview

The keyauth middleware implements a flexible API key authentication system with support for multiple key sources (headers, query parameters, and cookies) and customizable validation logic. Key Components:
  1. Key Extraction: The middleware parses the KeyLookup option to determine where to extract the API key from:
    • Header extraction with optional auth scheme prefix support
    • Query parameter extraction
    • Cookie extraction
  2. Validation Pipeline:
    • Extract key from the configured source
    • Return 401 Unauthorized if key is missing
    • Execute custom validator function
    • Return 403 Forbidden if validation fails or returns error
    • Store validated key in request context for downstream handlers
  3. Context Storage: Validated keys are stored using a private contextKey type, ensuring type-safe retrieval and preventing context key collisions.
  4. Error Handling: The middleware provides two error handling paths:
    • Custom error handler (if configured)
    • Default handler: 401 for missing keys, 403 for invalid keys or validation errors

Key Extraction Logic

Validator Function

The KeyValidator function signature:
Return Values:
  • (true, nil) - Key is valid, allow request
  • (false, nil) - Key is invalid, return 403 Forbidden
  • (_, error) - Validation error occurred, return 403 with error

Static Key Validation

The ValidateKeys helper creates a validator using a map for O(1) lookup:

Security Considerations

  1. Key Generation - Use cryptographically secure random keys
  2. Key Storage - Hash keys in database, never store plain text
  3. Key Rotation - Support key rotation without downtime
  4. Scoping - Consider scoped keys with limited permissions
  5. Logging - Log key usage but not full keys

Secure Key Generation

Best Practices

  • Use different keys for different environments
  • Implement key expiration
  • Add rate limiting per key
  • Log API key usage for auditing
  • Support multiple keys per user/service
  • Provide key management API

Testing

The keyauth middleware includes comprehensive test coverage for all functionality:

Running Tests