From 4a8d3291d3ec9e06b4c3e0710ff49fa78179d94e Mon Sep 17 00:00:00 2001 From: yumoqing Date: Wed, 22 Apr 2026 18:43:32 +0800 Subject: [PATCH] Add Bearer token authentication support for Authorization header --- SECURITY.md | 4 +++- config.yaml | 9 ++++++--- main.py | 13 +++++++++++-- 3 files changed, 20 insertions(+), 6 deletions(-) diff --git a/SECURITY.md b/SECURITY.md index 89434f6..a01a5f6 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -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 ` 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 diff --git a/config.yaml b/config.yaml index 1b2b804..09050e1 100644 --- a/config.yaml +++ b/config.yaml @@ -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: diff --git a/main.py b/main.py index c10eef6..c3d335f 100644 --- a/main.py +++ b/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")