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

DRF Api-Key认证报错:HasAPIKey无authenticate属性求解

问题原因与解决方法

核心错误

你把权限类HasAPIKey错误地配置到了DRF的DEFAULT_AUTHENTICATION_CLASSES中。HasAPIKey是用来校验权限的类,并不具备认证类要求的authenticate方法,这就是导致'HasAPIKey' object has no attribute 'authenticate'错误的直接原因。

正确配置示例

1. 全局配置修正

将认证类替换为该库提供的APIKeyAuthentication,权限类可按需全局设置或在视图中单独配置:

REST_FRAMEWORK = {
    # 配置API Key认证类
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_api_key.authentication.APIKeyAuthentication',
        # 保留原有的Session认证等(如果需要)
        'rest_framework.authentication.SessionAuthentication',
    ],
    # 可选:全局设置权限类,也可以只在视图中单独设置
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework_api_key.permissions.HasAPIKey',
    ]
}

2. 视图类修正

视图中使用IsAuthenticated | HasAPIKey表示允许登录用户或持有有效API Key的请求访问,注意确保导入正确的类:

from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
from rest_framework_api_key.permissions import HasAPIKey
from rest_framework.response import Response

class TestingApiKey(APIView):
    permission_classes = [IsAuthenticated | HasAPIKey]
    
    def post(self, request):
        # 这里添加你的业务逻辑
        return Response({"message": "请求成功"})

3. 正确的CURL请求格式

该库支持三种合法的API Key传递方式,注意格式正确:

  • 方式1:Authorization头(推荐)
curl --location --request POST 'http://127.0.0.1:8000/api/test' \
--header 'Authorization: Api-Key TiJwEHau.MF4ov6E3iz3C9KNNRAGdryH1tXfkjz8r' \
--header 'Content-Type: application/json' \
--data-raw '{
    "username" : "Testing",
    "Password" : "Testing123"
}'
  • 方式2:X-Api-Key头
curl --location --request POST 'http://127.0.0.1:8000/api/test' \
--header 'X-Api-Key: TiJwEHau.MF4ov6E3iz3C9KNNRAGdryH1tXfkjz8r' \
--header 'Content-Type: application/json' \
--data-raw '{
    "username" : "Testing",
    "Password" : "Testing123"
}'
  • 方式3:Api-Key头
curl --location --request POST 'http://127.0.0.1:8000/api/test' \
--header 'Api-Key: TiJwEHau.MF4ov6E3iz3C9KNNRAGdryH1tXfkjz8r' \
--header 'Content-Type: application/json' \
--data-raw '{
    "username" : "Testing",
    "Password" : "Testing123"
}'

4. 必要前置步骤

确保你已经完成:

  • 执行数据库迁移:python manage.py migrate(该库需要创建存储API Key的表)
  • 通过Django Admin或代码创建有效的API Key(只有数据库中存在的Key才能通过校验)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 11:31:02