gpt4 book ai didi

django - 如何在 `APIClient`中的 `django rest_framework test` header 中添加身份验证 token

转载 作者:行者123 更新时间:2023-12-03 11:57:14 32 4
gpt4 key购买 nike

我正在使用oauth2_provider作为rest_framework。我正在尝试为我的api编写测试用例。我已经获得了访问 token 。但是我无法使用access token中的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">

最佳答案

由于您正在curl中使用Authorization: Bearer,因此还应该使用带client.credentials字的Bearer而不是Token:

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

关于django - 如何在 `APIClient`中的 `django rest_framework test` header 中添加身份验证 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50678609/

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