1

I implemented custom authentication, as described in 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)

In my settings:

# settings.py

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

It works as expected during tests:

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)

However when I test with curl and locally running server, there is no X_SECRET_KEY header found in request.META. It is printing None in terminal, while received key is expected.

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

Could you give a hint, what might be a problem with that?

AmirM
  • 1,089
  • 1
  • 12
  • 26

1 Answers1

2

The headers variables are uppercase and prefixed with "HTTP_". This is general to Django, dunno about other languages / frameworks.

See https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/authentication.py#L23 for example.

Linovia
  • 19,812
  • 4
  • 47
  • 48