gpt4 book ai didi

python - 如何使用 REST Framework JWT 测试身份验证?

转载 作者:太空狗 更新时间:2023-10-29 21:20:49 24 4
gpt4 key购买 nike

基于 JWT 的身份验证可以很好地使用从移动设备和“高级休息客户端”发送的 POST 请求,但在使用 Django 测试客户端时会失败。客户端在请求时成功接收到 token ,但在尝试使用该 token 访问受限 View 时会收到以下响应。

"Authentication credentials were not provided."

测试用例:

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

限制 View :

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 测试客户端进行。

关于python - 如何使用 REST Framework JWT 测试身份验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33066265/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com