22

ビューの1つでTokenAuthenticationを使用しようとしています。https://www.django-rest-framework.org/api-guide/authentication/に記載されているように、ログインから受け取ったトークンを、送信するリクエストに「Authorization」というHTTPヘッダーとして追加します。

問題は、私のユニットテストで認証が失敗することです。TokenAuthenticationクラスを調べると、チェックされているヘッダーが「Authorization」ではなく「HTTP_AUTHORIZATION」であることがわかります。

私が使用しているビュー:

class DeviceCreate(generics.CreateAPIView):
    model = Device
    serializer_class = DeviceSerializer

    authentication_classes = (TokenAuthentication,)
    permission_classes = (IsAuthenticated,)

ヘッダーを「HTTP_AUTHORIZATION」に変更することは機能しているようですが、何かがおかしいと感じています。

私は何かが足りないのですか?

4

2 に答える 2

22

Looking into the TokenAuthentication class I see that the header being checked is 'HTTP_AUTHORIZATION' and not 'Authorization'

Not quite true, when doing lookups in the request META dict, the headers that it's actually looking for are with out the preceeding HTTP_, so request.META.get('HTTP_AUTHORIZATION', '') is actually looking up the Authorization header in the request.

The problem is that in my unittests the authentication fails Changing the header to 'HTTP_AUTHORIZATION' seems to work

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 the Authorization 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.META

Edit:

Django docs on looking up headers in request.META:

With the exception of CONTENT_LENGTH and CONTENT_TYPE, as given above, any HTTP headers in the request are converted to META keys by converting all characters to uppercase, replacing any hyphens with underscores and adding an HTTP_ prefix to the name. So, for example, a header called X-Bender would be mapped to the META key HTTP_X_BENDER.

Django docs on setting headers with the test client:

However, you can use keywords arguments to specify some default headers. For example, this will send a User-Agent HTTP header in each request:

c = Client(HTTP_USER_AGENT='Mozilla/5.0')

于 2013-02-27T14:24:36.897 に答える
7

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:

RewriteEngine on
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization},L]
于 2015-09-24T17:11:25.650 に答える