Files
Mofox-Core/src/common/security.py
minecraft1024a 334df4d87f refactor(plugin_system): 移除路由级认证,引入端点级安全依赖
之前的插件路由认证机制通过在 `RouterInfo` 中设置 `auth_required` 标志,对整个路由组件统一应用API密钥验证。这种方式缺乏灵活性,无法对单个端点进行细粒度的安全控制。

本次重构移除了 `auth_required` 机制,转而引入一个可重用的 FastAPI 依赖项 `VerifiedDep`。插件开发者现在可以按需将其应用到需要保护的特定端点上,从而实现更灵活、更精确的访问控制。

`hello_world_plugin` 已更新,以演示新的认证方式。

BREAKING CHANGE: 移除了 `RouterInfo` 中的 `auth_required` 属性。所有依赖此属性进行认证的插件路由都需要更新,改为在需要保护的端点上使用 `VerifiedDep` 依赖项。
2025-11-19 23:58:48 +08:00

37 lines
1.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from fastapi import Depends, HTTPException, Security
from fastapi.security.api_key import APIKeyHeader
from starlette.status import HTTP_401_UNAUTHORIZED, HTTP_403_FORBIDDEN
from src.common.logger import get_logger
from src.config.config import global_config as bot_config
logger = get_logger("security")
API_KEY_HEADER = "X-API-Key"
api_key_header_auth = APIKeyHeader(name=API_KEY_HEADER, auto_error=True)
async def get_api_key(api_key: str = Security(api_key_header_auth)) -> str:
"""
FastAPI 依赖项用于验证API密钥。
从请求头中提取 X-API-Key 并验证它是否存在于配置的有效密钥列表中。
"""
valid_keys = bot_config.plugin_http_system.plugin_api_valid_keys
if not valid_keys:
logger.warning("API密钥认证已启用但未配置任何有效的API密钥。所有请求都将被拒绝。")
raise HTTPException(
status_code=HTTP_401_UNAUTHORIZED,
detail="服务未正确配置API密钥",
)
if api_key not in valid_keys:
logger.warning(f"无效的API密钥: {api_key}")
raise HTTPException(
status_code=HTTP_403_FORBIDDEN,
detail="无效的API密钥",
)
return api_key
# 创建一个可重用的依赖项,供插件开发者在其需要验证的端点上使用
# 用法: @router.get("/protected_route", dependencies=[VerifiedDep])
# 或者: async def my_endpoint(_=VerifiedDep): ...
VerifiedDep = Depends(get_api_key)