统一的灵活认证函数,支持多种认证方式 此函数可以直接用作 FastAPI 的 Depends 依赖 支持的认证方式: - URL 参数: key - HTTP 头部: Authorization (Bearer token) - HTTP 头部: x-api-key - HTTP 头部: access_token - HTTP 头部: x-goog-api-key - HTTP 头部: x-anthropic-auth-token - HTTP 头部:
(
request: Request,
authorization: Optional[str] = Header(None),
x_api_key: Optional[str] = Header(None, alias="x-api-key"),
access_token: Optional[str] = Header(None, alias="access_token"),
x_goog_api_key: Optional[str] = Header(None, alias="x-goog-api-key"),
x_anthropic_auth_token: Optional[str] = Header(None, alias="x-anthropic-auth-token"),
anthropic_auth_token: Optional[str] = Header(None, alias="anthropic-auth-token"),
key: Optional[str] = Query(None)
)
| 149 | # ====================== Authentication Functions ====================== |
| 150 | |
| 151 | async def authenticate_flexible( |
| 152 | request: Request, |
| 153 | authorization: Optional[str] = Header(None), |
| 154 | x_api_key: Optional[str] = Header(None, alias="x-api-key"), |
| 155 | access_token: Optional[str] = Header(None, alias="access_token"), |
| 156 | x_goog_api_key: Optional[str] = Header(None, alias="x-goog-api-key"), |
| 157 | x_anthropic_auth_token: Optional[str] = Header(None, alias="x-anthropic-auth-token"), |
| 158 | anthropic_auth_token: Optional[str] = Header(None, alias="anthropic-auth-token"), |
| 159 | key: Optional[str] = Query(None) |
| 160 | ) -> str: |
| 161 | """ |
| 162 | 统一的灵活认证函数,支持多种认证方式 |
| 163 | |
| 164 | 此函数可以直接用作 FastAPI 的 Depends 依赖 |
| 165 | |
| 166 | 支持的认证方式: |
| 167 | - URL 参数: key |
| 168 | - HTTP 头部: Authorization (Bearer token) |
| 169 | - HTTP 头部: x-api-key |
| 170 | - HTTP 头部: access_token |
| 171 | - HTTP 头部: x-goog-api-key |
| 172 | - HTTP 头部: x-anthropic-auth-token |
| 173 | - HTTP 头部: anthropic-auth-token |
| 174 | |
| 175 | Args: |
| 176 | request: FastAPI Request 对象 |
| 177 | authorization: Authorization 头部值(自动注入) |
| 178 | x_api_key: x-api-key 头部值(自动注入) |
| 179 | access_token: access_token 头部值(自动注入) |
| 180 | x_goog_api_key: x-goog-api-key 头部值(自动注入) |
| 181 | x_anthropic_auth_token: x-anthropic-auth-token 头部值(自动注入) |
| 182 | anthropic_auth_token: anthropic-auth-token 头部值(自动注入) |
| 183 | key: URL 参数 key(自动注入) |
| 184 | |
| 185 | Returns: |
| 186 | 验证通过的token |
| 187 | |
| 188 | Raises: |
| 189 | HTTPException: 认证失败时抛出异常 |
| 190 | |
| 191 | 使用示例: |
| 192 | @router.post("/endpoint") |
| 193 | async def endpoint(token: str = Depends(authenticate_flexible)): |
| 194 | # token 已验证通过 |
| 195 | pass |
| 196 | """ |
| 197 | password = await get_api_password() |
| 198 | token = None |
| 199 | auth_method = None |
| 200 | |
| 201 | # 1. 尝试从 URL 参数 key 获取(Google 官方标准方式) |
| 202 | if key: |
| 203 | token = key |
| 204 | auth_method = "URL parameter 'key'" |
| 205 | |
| 206 | # 2. 尝试从 x-goog-api-key 头部获取(Google API 标准方式) |
| 207 | elif x_goog_api_key: |
| 208 | token = x_goog_api_key |
nothing calls this directly
no test coverage detected