Add Bearer token authentication support for Authorization header
This commit is contained in:
parent
57fbe3a6c5
commit
4a8d3291d3
@ -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
|
||||
|
||||
@ -17,6 +17,12 @@ 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:
|
||||
@ -24,9 +30,6 @@ security:
|
||||
# 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:
|
||||
# Trust X-Forwarded-For header from these proxies
|
||||
|
||||
13
main.py
13
main.py
@ -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")
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user