Add Bearer token authentication support for Authorization header

This commit is contained in:
yumoqing 2026-04-22 18:43:32 +08:00
parent 57fbe3a6c5
commit 4a8d3291d3
3 changed files with 20 additions and 6 deletions

View File

@ -15,8 +15,10 @@ The service uses a `config.yaml` file for configuration. Key security features i
### API Key Authentication
- Enable with `security.enable_api_key: true`
- Choose authentication method: `header` (custom header) or `bearer` (Authorization header)
- For `bearer` method, use `Authorization: Bearer <apikey>` header
- For `header` method, configure custom header name via `security.api_key_header`
- Define valid API keys in `security.api_keys`
- Customizable header name via `security.api_key_header`
### Nginx Integration
- Real IP detection from X-Forwarded-For header

View File

@ -17,15 +17,18 @@ security:
# Enable API key authentication
enable_api_key: false
# Authentication method: "header" or "bearer"
auth_method: "header"
# Header name for API key (used when auth_method is "header")
api_key_header: "X-API-Key"
# List of valid API keys
# Each key can have a description and optional expiration
api_keys:
# - key: "your-api-key-here"
# description: "Main production key"
# expires_at: null # null means never expires, or use ISO format: "2025-12-31T23:59:59Z"
# Header name for API key (default: X-API-Key)
api_key_header: "X-API-Key"
# Nginx integration settings
nginx:

13
main.py
View File

@ -138,8 +138,17 @@ def validate_ip_and_apikey():
# API Key validation
if config['security']['enable_api_key']:
api_key_header = config['security']['api_key_header']
provided_key = request.headers.get(api_key_header)
provided_key = None
if config['security']['auth_method'] == 'bearer':
# Check Authorization header for Bearer token
auth_header = request.headers.get("authorization")
if auth_header and auth_header.lower().startswith("bearer "):
provided_key = auth_header[7:].strip() # Remove "Bearer " prefix
else:
# Check custom header (default: X-API-Key)
api_key_header = config['security']['api_key_header']
provided_key = request.headers.get(api_key_header)
if not provided_key:
raise HTTPException(status_code=401, detail="API key required")