2016-10-03 119 views
0

我实现了自定义的认证,在docs自定义头没有被加入到request.META Django的REST框架

# 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和本地r unning服务器,在request.META中找不到X_SECRET_KEY标头。在终端打印None,一边收到钥匙预计。

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

你能给一个提示,可能是什么问题呢?

回答