Security Middleware
The security middleware provides a robust set of security measures for protecting API endpoints and file uploads. It combines multiple security features including CORS, CSRF protection, secure headers, rate limiting, and authentication.
Configuration
The security configuration is defined in @/config
:
Implementation
The security middleware combines multiple security features using Hono's middleware system:
Security Features
Secure Headers
Implements strict security headers to protect against common web vulnerabilities:
CORS Protection
Implements Cross-Origin Resource Sharing (CORS) with configurable origins:
CSRF Protection
Protects against Cross-Site Request Forgery attacks:
Rate Limiting
Implements rate limiting to prevent abuse:
Authentication
Handles user authentication with configurable public paths:
Usage
Apply the security middleware globally in your application:
Headers Configuration
Allowed Headers
The middleware supports various headers required for file uploads and API communication:
- Standard headers (Content-Type, Authorization)
- TUS protocol headers (Upload-Length, Upload-Metadata, etc.)
- Custom headers (X-Health-Check, X-Response-Time, etc.)
Exposed Headers
Headers that are exposed to the client:
- Upload-related headers (Location, Upload-Offset, etc.)
- Rate limiting headers (X-RateLimit-*)
- Authentication headers (WWW-Authenticate)
- Monitoring headers (X-Health-Check, X-Response-Time)
Best Practices
-
Origin Configuration
- Maintain a strict list of allowed origins
- Use environment-specific configurations
- Regularly review and update allowed origins
-
Header Management
- Keep allowed headers list minimal
- Regularly audit exposed headers
- Update header configurations based on requirements
-
Security Policies
- Implement strict Content Security Policy
- Enable all relevant security headers
- Regular security audits and updates
-
Rate Limiting
- Configure appropriate rate limits
- Monitor rate limit effectiveness
- Adjust limits based on usage patterns
-
Authentication
- Maintain updated public paths list
- Implement proper token validation
- Regular security token rotation
Error Handling
The middleware provides standardized error responses:
CORS Error
Rate Limit Error
Authentication Error
Last updated on