Middleware
Application Kit provides Django middleware for handling CORS, authentication, and error responses.
Note
Middleware is currently only available for Django. FastAPI handles these concerns through dependencies and exception handlers.
ApplicationKitApiMiddleware
The primary middleware for API services. It provides:
- Exception handling with user-friendly error responses
- CORS preflight request handling
- Origin validation
Installation
Add to your Django MIDDLEWARE setting:
MIDDLEWARE_API = [
# ... other middleware
"application_kit.django.middleware.ApplicationKitApiMiddleware",
]
Exception Handling
The middleware catches all exceptions and returns them in a consistent JSON format:
{
"error": "Error message here"
}
CORS Handling
For OPTIONS requests (preflight), the middleware:
- Sets
Access-Control-Request-Method: * - Sets
Access-Control-Request-Headers: * - Sets
Access-Control-Max-Age: 86400(24 hours) - Sets
Access-Control-Allow-Credentials: true - Sets
Vary: Origin, X-Api-Key
Origin Validation
The middleware validates the Origin header based on the token type:
| Token Type | Validation |
|---|---|
| Public Key | Checks against the key's allowed domains (from cache if available) |
| User Token | Checks against CORS_ORIGIN_WHITELIST configuration |
| Private Key | Only supports OPTIONS when using X-Api-Key header |
Warning
Origin validation can return 401 or 403 responses for preflight requests if the origin is not allowed.
ApplicationKitBaseMiddleware
A simpler middleware for internal services (like the authentication service itself).
Installation
# For internal services (like authentication service)
MIDDLEWARE_BASE = [
# ... other middleware
"application_kit.django.middleware.ApplicationKitBaseMiddleware",
]
Features
- Handles
OPTIONSrequests - Matches
Originagainst a whitelist
Note
This middleware is primarily used by the authentication service.
Configuration
CORS Whitelist
Configure allowed origins in your application.json:
{
"configurations": [
{
"name": "CORS_ORIGIN_WHITELIST",
"type": "list",
"test_value": ["localhost", "example.com"]
}
]
}
Access it via settings:
"""CORS whitelist configuration example."""
from application_kit.settings import get_cors_origin_whitelist
whitelist = get_cors_origin_whitelist()
# In develop environment, "localhost" is automatically added
Response Headers
The middleware sets these headers on responses:
| Header | Value | Description |
|---|---|---|
Access-Control-Allow-Origin |
Varies | The validated origin or * |
Access-Control-Allow-Credentials |
true |
Allow credentials |
Access-Control-Max-Age |
86400 |
Cache preflight for 24 hours |
Vary |
Origin, X-Api-Key |
Cache variation keys |