【问题标题】:Custom header is not added into request.META in Django Rest Framework自定义标头未添加到 Django Rest Framework 中的 request.META 中
【发布时间】:2016-10-03 08:57:58
【问题描述】:

我实现了自定义身份验证,如 docs 中所述

# custom_permissions.py

from rest_framework import authentication
from rest_framework import exceptions

class KeyAuthentication(authentication.BaseAuthentication):
    def authenticate(self, request):
        key = request.META.get('Authorization')
        print(key)
        if not key:
            raise exceptions.AuthenticationFailed('Authentication failed.')

        try:
            key = ApiKey.objects.get(key=key)
        except ApiKey.DoesNotExist:
            raise exceptions.AuthenticationFailed('Authentication failed.')

    return (key, None)

在我的设置中:

# settings.py

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'api_server.apps.api_v1.custom_permissions.KeyAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.AllowAny',
    ),
}

它在测试期间按预期工作:

def test_1(self):
    client = APIClient()
    client.credentials(X_SECRET_KEY='INVALID_KEY')
    response = client.get('/v1/resource/')
    self.assertEqual(response.status_code, 403)
    self.assertEqual(response.data, {'detail': 'Authentication failed.'})

def test_2(self):
    client = APIClient()
    client.credentials(X_SECRET_KEY='FEJ5UI')
    response = client.get('/v1/resource/')
    self.assertEqual(response.status_code, 200)

但是,当我使用 curl 和本地运行的服务器进行测试时,在 request.META 中找不到 X_SECRET_KEY 标头。它正在终端打印None,而收到的密钥是预期的。

$ curl -X GET localhost:8080/v1/resource/ -H "X_SECRET_KEY=FEJ5UI"
{'detail': 'Authentication failed.'}

您能否给个提示,这可能是什么问题?

【问题讨论】:

    标签: django-rest-framework custom-authentication


    【解决方案1】:

    标头变量为大写,并以“HTTP_”为前缀。这对 Django 来说是通用的,不知道其他语言/框架。

    例如,请参阅https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/authentication.py#L23

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-04
      • 1970-01-01
      • 1970-01-01
      • 2013-01-13
      • 1970-01-01
      • 1970-01-01
      • 2016-05-29
      • 1970-01-01
      相关资源
      最近更新 更多