首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在` `django rest_framework test`的`APIClient`头部添加鉴权token

如何在` `django rest_framework test`的`APIClient`头部添加鉴权token
EN

Stack Overflow用户
提问于 2018-06-04 18:35:45
回答 1查看 9.8K关注 0票数 10

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

代码语言:javascript
复制
curl -H "Authorization: Bearer <your_access_token>" http://localhost:8000/api/v1/users/current/

我试过了

代码语言:javascript
复制
client.get('/api/v1/users/current/',  headers={'Authorization': 'Bearer {}'.format(self.access_token)})

代码语言:javascript
复制
client.credentials(HTTP_AUTHORIZATION='Token ' + self.access_token)

下面是代码片段的一部分

代码语言:javascript
复制
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)})

我得到了回应

代码语言:javascript
复制
<HttpResponseForbidden status_code=403, "text/html; charset=utf-8">
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-04 18:41:37

由于您在curl中使用Authorization: Bearer,因此还应将client.credentialsBearer word一起使用,而不是Token

代码语言:javascript
复制
client.credentials(HTTP_AUTHORIZATION='Bearer ' + self.access_token)
票数 19
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50678609

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档