基于JWT的身份验证在通过移动设备和“高级 REST 客户端”发送的 POST 请求中运作良好,但是在使用 Django 测试客户端时会失败。当请求获得令牌时,客户端可以成功接收令牌,但是在使用该令牌访问受限视图时,客户端会收到以下响应:
“未提供身份验证凭据。”
测试用例:
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.get('/api/someurl', {}, HTTP_AUTHORIZATION='Token {}'.format(self.token))
- Joris Kok