【发布时间】:2016-01-09 01:19:19
【问题描述】:
基于 JWT 的身份验证在使用从移动设备和“高级休息客户端”发送的 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')
我在测试用例中遗漏了什么吗?
【问题讨论】:
标签: python django django-rest-framework jwt