首页 > 解决方案 > 如何在`django rest_framework test`的`APIClient`的标头中添加身份验证令牌

问题描述

我正在使用oauth2_provider我的rest_framework. 我正在尝试为我的 api 编写测试用例。我已获得访问令牌。但我无法使用access tokenin验证用户身份,APIClient 我希望让这个 curl 命令与APIClient.

curl -H "Authorization: Bearer <your_access_token>" http://localhost:8000/api/v1/users/current/

我努力了

client.get('/api/v1/users/current/',  headers={'Authorization': 'Bearer {}'.format(self.access_token)})

client.credentials(HTTP_AUTHORIZATION='Token ' + self.access_token)

这是片段的一部分

from rest_framework.test import APIClient    
from rest_framework.test import APITestCase
....

class APITest(APITestCase):
    def setUp(self):
        ...
        self.client = APIClient()
        ...
        response = self.client.post('/api/v1/oauth2/token/', post_data)
        self.access_token = response.json()['access_token']

    def test_get_current_user(self):
        client.get('/api/v1/users/current/',  headers={'Authorization': 'Bearer {}'.format(self.access_token)})

我得到回应

<HttpResponseForbidden status_code=403, "text/html; charset=utf-8">

标签: djangodjango-rest-frameworkdjango-testingdjango-unittestoauth-provider

解决方案


由于您Authorization: Bearer在 curl 中使用,您还应该使用client.credentialswith Bearerword 而不是Token

client.credentials(HTTP_AUTHORIZATION='Bearer ' + self.access_token)

推荐阅读