如何在django rest_framework test中的APIClient标头中添加身份验证令牌 [英] How to add authentication token in header of `APIClient` in `django rest_framework test`

查看:235
本文介绍了如何在django rest_framework test中的APIClient标头中添加身份验证令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为rest_framework使用oauth2_provider.我正在尝试为我的api编写测试用例.我已经获得了访问令牌.但是我无法使用APIClient中的access token来认证用户 我希望将此命令与APIClient一起使用.

I am using oauth2_provider for my rest_framework. I am trying to write test case for my api. I have obtained an access token. But I am not able to authenticate user using access token in APIClient I am looking to get this curl command work with 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,因此还应该使用带Bearer字词的client.credentials而不是Token:

Since you are using Authorization: Bearer in curl, you should also use client.credentials with Bearer word instead of Token:

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

这篇关于如何在django rest_framework test中的APIClient标头中添加身份验证令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆