I'm trying to use the TokenAuthentication with one of my views. As documented in https://www.django-rest-framework.org/api-guide/authentication/, I add the token I received from the login as an HTTP header called: 'Authorization' in the request I send.
The problem is that in my unittests the authentication fails. Looking into the TokenAuthentication class I see that the header being checked is 'HTTP_AUTHORIZATION' and not 'Authorization'
The view I'm using:
class DeviceCreate(generics.CreateAPIView):
model = Device
serializer_class = DeviceSerializer
authentication_classes = (TokenAuthentication,)
permission_classes = (IsAuthenticated,)
Changing the header to 'HTTP_AUTHORIZATION' seems to work, but something feels wrong.
Am I missing anything?
Not quite true, when doing lookups in the request
META
dict, the headers that it's actually looking for are with out the preceedingHTTP_
, sorequest.META.get('HTTP_AUTHORIZATION', '')
is actually looking up theAuthorization
header in the request.I havn't double checked how the test client looks but I believe that setting
HTTP_AUTHORIZATION
is what you need to do get the equivalent of actually setting theAuthorization
header. If you actually made an http request you should find that setting the auth header works exactly as you'd expect.See
request.META
documentation here: https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpRequest.METAEdit:
Django docs on looking up headers in
request.META
:Django docs on setting headers with the test client:
Tom's answer is fine, but not complete.
Your code can work fine in dev environnement (with
runserver
) but if you try it in a WSGI server (Apache in my case), the server can strip out the Authorization header !You can find on Boone's Blog a good fix for your Apache conf to keep the Authorization header in the request and make it work great: