如何使用REST框架JWT测试身份验证?

2024-06-01 11:19:42 发布

您现在位置:Python中文网/ 问答频道 /正文

基于JWT的身份验证在使用从mobile和“高级rest客户端”发送的POST请求时工作良好,但是在使用Django测试客户端时失败。 客户端在请求时成功接收令牌,但在尝试使用该令牌访问受限视图时,它将获得以下响应。

"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

受限视图:

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')

我在测试用例中遗漏了什么吗?


Tags: theselfclienttoken视图json客户端get
3条回答

好吧,下面的问题似乎已经解决了:

而不是:

response = self.client.post("/auth/api/authenticated/", {}, Authorization='JWT ' + token)

我不得不写:

response = self.client.post("/auth/api/authenticated/", {}, HTTP_AUTHORIZATION='JWT {}'.format(token))

身份验证现在也可以通过Django测试客户机工作。

还要记住,在创建用户时,必须对密码使用哈希版本。E、 g.:

User(email='TestUser@email.io', password=make_password('TestPassword'))

Using djangos password hashers

当调用/auth/api/get_token/时,必须使用清除大小写密码。E、 g.:

response = self.client.post("/auth/api/get_token/", {'email': 'TestUser@email.io', 'password': 'TestPassword'})

我花了一段时间才发现请求响应了'non_field_errors': ['Unable to log in with provided credentials.'],因为我在创建用户时没有使用哈希器。

注意,当通过OAuth2使用JWT时,以下代码可能有助于创建身份验证凭据:

self.client.post("/auth/api/authenticated/", {}, HTTP_AUTHORIZATION='Bearer {0}'.format(token))

然而,Django Rest框架包括验证请求的脚手架: http://www.django-rest-framework.org/api-guide/testing/#forcing-authentication

此外,这里还有一些有趣的测试: https://github.com/jpadilla/django-jwt-auth/blob/master/tests/test_mixins.py

相关问题 更多 >