You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取DRF中使用的API Key前缀?drf-api-key授权监控

实现drf-api-key的API Key监控(关联数据库连接)

你遇到headers.get("Authorization")返回None的问题,大概率是因为drf-api-key的认证流程已完成,或是项目配置了自定义API Key请求头(比如X-Api-Key)。以下是几种可行的实现方案:

方案1:重写APIKeyAuthentication类,注入API Key信息

drf-api-key的核心认证类是APIKeyAuthentication,重写它的authenticate方法,在认证成功后将API Key的名称、前缀存入请求对象,后续数据库操作时即可直接获取:

from rest_framework_api_key.authentication import APIKeyAuthentication

class MonitoredAPIKeyAuthentication(APIKeyAuthentication):
    def authenticate(self, request):
        auth_result = super().authenticate(request)
        if auth_result:
            _, api_key = auth_result
            # 将API Key信息绑定到request对象
            request.api_key_name = api_key.name
            request.api_key_prefix = api_key.prefix
        return auth_result

之后在项目配置中替换默认认证类:

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'your_app.authentication.MonitoredAPIKeyAuthentication',
        # 其他认证类...
    ],
}

方案2:结合Django信号监听数据库连接事件

如果需要直接关联数据库连接动作,可以利用Django的connection_created信号,配合线程本地存储获取当前请求的API Key:

from django.db.backends.signals import connection_created
from threading import local

# 线程本地存储,避免多线程环境下请求信息混乱
_thread_local = local()

class RequestMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        _thread_local.request = request
        response = self.get_response(request)
        del _thread_local.request
        return response

def log_db_api_key(sender, connection, **kwargs):
    current_request = getattr(_thread_local, 'request', None)
    if current_request and hasattr(current_request, 'api_key_name'):
        # 此处可将API Key信息写入日志、监控系统等
        print(f"DB connection via API Key: {current_request.api_key_name} (prefix: {current_request.api_key_prefix})")

# 绑定信号
connection_created.connect(log_db_api_key)

记得将上述中间件添加到settings的MIDDLEWARE列表中。

方案3:直接从认证后的request对象提取API Key

在已通过认证的视图或序列化器中,可直接从request.auth获取API Key实例(drf-api-key认证成功后,request.auth会返回对应APIKey对象):

def your_view(request):
    if request.auth:
        api_key_name = request.auth.name
        api_key_prefix = request.auth.prefix
        # 记录或使用该信息
        print(f"Current API Key: {api_key_name}")
    # 后续数据库操作逻辑...

关于Authorization头返回None的补充说明

drf-api-key默认检查Authorization: Api-Key <your-key>格式的请求头,若项目使用自定义请求头(如X-Api-Key),需在认证类中配置:

class MonitoredAPIKeyAuthentication(APIKeyAuthentication):
    header = 'X-Api-Key'  # 指定自定义请求头

内容的提问来源于stack exchange,提问作者Marlon Bucalan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 06:01:01