2015-10-11 17 views
5

JWTベースの認証は、モバイルと "高度なレストクライアント"から送信されたPOST要求を使用してうまく機能しますが、Djangoテストクライアントを使用すると失敗します。 クライアントは要求時に正常にトークンを受信しますが、そのトークンを使用して制限付きビューにアクセスしようとすると、次の応答が返されます。REST Framework JWTを使用して認証をテストする方法は?

"認証資格情報が提供されていませんでした。

テスト・ケース:

def test_get_token(self): 
     response = self.client.post("/auth/api/get_token/", {"username": "Heffalumps", "password": "Woozles"}) 
     self.assertEqual(response.status_code, 200, "The token should be successfully returned.") 

     response_content = json.loads(response.content.decode('utf-8')) 
     token = response_content["token"] 

     # The following request fails 
     response = self.client.post("/auth/api/authenticated/", {}, Authorization='JWT ' + token) 
     response_content = json.loads(response.content.decode('utf-8')) 

     self.assertEqual(response_content["authenticated"], "mooh", "The user should be able to access this endpoint.") 

テストクライアントからの発信要求: enter image description here

制限ビュー:

class RestrictedView(APIView): 
    permission_classes = (permissions.IsAuthenticated,) 
    authentication_classes = (JSONWebTokenAuthentication,) 

    def post(self, request): 

     response_data = json.dumps({"authenticated": "mooh"}) 

     return HttpResponse(response_data, content_type='application/json') 

私はテストケースから何かが足りないのですか?私が書かなければならなかった

response = self.client.post("/auth/api/authenticated/", {}, Authorization='JWT ' + token) 

response = self.client.post("/auth/api/authenticated/", {}, HTTP_AUTHORIZATION='JWT {}'.format(token)) 

認証のようにDjangoのテストクライアントを介して機能するようになりました

の代わりに:

答えて

9

さて、次は、問題を解決したようですよくOAuth2を介してJWTを使用する場合

+0

ありがとう!私の日を救った。 –

+0

トークン認証でDjango Rest APIを使用していましたが、それを次のように変更する必要がありました: response = self.client.get( '/ api/someurl'、{}、HTTP_AUTHORIZATION = 'トークン{}'。 )) –

0

これは、ことに注意することは有用であってもよいし、次のコードは、認証証明書作成:

self.client.post("/auth/api/authenticated/", {}, HTTP_AUTHORIZATION='Bearer {0}'.format(token)) 

ジャンゴレストフレームワークを、しかし、要求を認証するための足場を含む: http://www.django-rest-framework.org/api-guide/testing/#forcing-authentication

さらに、いくつか興味深いテストがあります: https://github.com/jpadilla/django-jwt-auth/blob/master/tests/test_mixins.py

関連する問題