django - 如何在`django rest_framework test`的`APIClient`的标头中添加身份验证令牌
问题描述
我正在使用oauth2_provider
我的rest_framework
. 我正在尝试为我的 api 编写测试用例。我已获得访问令牌。但我无法使用access token
in验证用户身份,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">
解决方案
由于您Authorization: Bearer
在 curl 中使用,您还应该使用client.credentials
with Bearer
word 而不是Token
:
client.credentials(HTTP_AUTHORIZATION='Bearer ' + self.access_token)
推荐阅读
- elasticsearch - 如何在没有偏移的情况下对 Elasticsearch 中的嵌套对象进行分页?
- excel - 在 Excel 工作表中搜索另一个工作表中的关键字列表
- java - 由于无法解析端点而导致的 Apache camel cron 错误:cron
- php - 不能在 Laravel 中使用 Illuminate\\Http\\JsonResponse 类型的对象作为数组
- ios - 使用 UIScreen 获取屏幕宽度以自动适应内容?
- javascript - Webhook 比较问题中的 Instamojo 消息身份验证代码
- html - How to 'href' to the element even to the top margin of each div?
- python - 将数据集从 google drive 上传到 google colab
- mysql - Mysql将行转换为具有varchar值的列
- arabic - 导出为 PDF 时,有什么方法可以从右到左开始我的阿拉伯语文本