djangodjango-rest-frameworkdjango-testingdjango-unittestoauth-provider

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


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">

Solution

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