File size: 1,430 Bytes
f6c1709
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
"""
API认证模块
提供API Key验证功能(用于API端点)
管理端点使用Session认证(见core/session_auth.py)
"""
from typing import Optional
from fastapi import HTTPException


def verify_api_key(api_key_value: str, authorization: Optional[str] = None) -> bool:
    """
    验证 API Key(支持多个密钥,用逗号分隔)

    Args:
        api_key_value: 配置的API Key值(如果为空则跳过验证,多个密钥用逗号分隔)
        authorization: Authorization Header中的值

    Returns:
        验证通过返回True,否则抛出HTTPException

    支持格式:
    1. Bearer YOUR_API_KEY
    2. YOUR_API_KEY

    多密钥配置示例:
    API_KEY=key1,key2,key3
    """
    # 如果未配置 API_KEY,则跳过验证
    if not api_key_value:
        return True

    # 检查 Authorization header
    if not authorization:
        raise HTTPException(
            status_code=401,
            detail="Missing Authorization header"
        )

    # 提取token(支持Bearer格式)
    token = authorization
    if authorization.startswith("Bearer "):
        token = authorization[7:]

    # 解析多个密钥(用逗号分隔)
    valid_keys = [key.strip() for key in api_key_value.split(",") if key.strip()]

    if token not in valid_keys:
        raise HTTPException(
            status_code=401,
            detail="Invalid API Key"
        )

    return True