How to add authentication token in header of `APIClient` in `django rest_framework test`

岁酱吖の 提交于 2019-12-08 21:36:23

问题


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/

I have tried

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

and

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

Here is the part of snippet

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)})

I am getting response

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

回答1:


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)


来源:https://stackoverflow.com/questions/50678609/how-to-add-authentication-token-in-header-of-apiclient-in-django-rest-framewo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!