Overview
Thekeyauth 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
| Option | Type | Default | Description |
|---|---|---|---|
Validator | KeyValidator | - | Function to validate API keys |
KeyLookup | string | "header:X-API-Key" | Where to find the key |
AuthScheme | string | "" | Scheme prefix for header lookup |
ErrorHandler | func(*mizu.Ctx, error) error | - | Custom error handler |
KeyLookup Format
TheKeyLookup option uses the format "source:name":
| Source | Example | Description |
|---|---|---|
header | "header:X-API-Key" | Read from header |
query | "query:api_key" | Read from query parameter |
cookie | "cookie:api_key" | Read from cookie |
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:-
Key Extraction: The middleware parses the
KeyLookupoption to determine where to extract the API key from:- Header extraction with optional auth scheme prefix support
- Query parameter extraction
- Cookie extraction
-
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
-
Context Storage: Validated keys are stored using a private
contextKeytype, ensuring type-safe retrieval and preventing context key collisions. -
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
TheKeyValidator function signature:
(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
TheValidateKeys helper creates a validator using a map for O(1) lookup:
Security Considerations
- Key Generation - Use cryptographically secure random keys
- Key Storage - Hash keys in database, never store plain text
- Key Rotation - Support key rotation without downtime
- Scoping - Consider scoped keys with limited permissions
- 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:| Test Case | Description | Expected Behavior |
|---|---|---|
| TestNew - valid key | Valid API key provided in X-API-Key header | Returns 200 OK, allows request through |
| TestNew - invalid key | Invalid API key provided | Returns 403 Forbidden, blocks request |
| TestNew - missing key | No API key provided | Returns 401 Unauthorized, blocks request |
| TestWithOptions_QueryLookup | API key provided via query parameter | Returns 200 OK when key is valid |
| TestWithOptions_CookieLookup | API key provided via cookie | Returns 200 OK when key is valid |
| TestWithOptions_AuthScheme | API key with “ApiKey” scheme in Authorization header | Strips scheme prefix, validates key, returns 200 OK |
| TestWithOptions_ErrorHandler | Custom error handler configured | Custom error handler is invoked, returns custom JSON response |
| TestWithOptions_ValidatorError | Validator returns error (e.g., database error) | Returns 403 Forbidden with error message |
| TestFromContext | Retrieve API key from context after validation | Returns the validated API key string |
| TestGet | Test Get() function as alias for FromContext() | Both functions return the same key value |
| TestValidateKeys - key1 | Static validator with “key1” in allowed list | Returns valid=true |
| TestValidateKeys - key2 | Static validator with “key2” in allowed list | Returns valid=true |
| TestValidateKeys - key3 | Static validator with “key3” in allowed list | Returns valid=true |
| TestValidateKeys - key4 | Static validator with “key4” not in allowed list | Returns valid=false |
| TestValidateKeys - empty | Static validator with empty string | Returns valid=false |
| TestWithOptions_Panics - no validator | Create middleware without validator | Panics with error message |
| TestWithOptions_Panics - invalid lookup | Create middleware with invalid KeyLookup format | Panics with error message |
| TestErrors | Verify error constants | ErrKeyMissing and ErrKeyInvalid return correct messages |
Running Tests
Related Middlewares
- basicauth - Username/password authentication
- bearerauth - Bearer token authentication
- ratelimit - Rate limiting