Mar*_*yyy 7 python django jwt django-rest-framework
基于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.")
Run Code Online (Sandbox Code Playgroud)
限制观点:
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')
Run Code Online (Sandbox Code Playgroud)
我错过了测试用例中的内容吗?
Mar*_*yyy 16
好的,以下似乎已经解决了这个问题:
代替:
response = self.client.post("/auth/api/authenticated/", {}, Authorization='JWT ' + token)
Run Code Online (Sandbox Code Playgroud)
我不得不写:
response = self.client.post("/auth/api/authenticated/", {}, HTTP_AUTHORIZATION='JWT {}'.format(token))
Run Code Online (Sandbox Code Playgroud)
身份验证现在也通过Django测试客户端工作.
| 归档时间: |
|
| 查看次数: |
5118 次 |
| 最近记录: |