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.")
制限ビュー:
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のテストクライアントを介して機能するようになりました
の代わりに:
ありがとう!私の日を救った。 –
トークン認証でDjango Rest APIを使用していましたが、それを次のように変更する必要がありました: response = self.client.get( '/ api/someurl'、{}、HTTP_AUTHORIZATION = 'トークン{}'。 )) –