14

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">
Sudheer K
  • 1,244
  • 2
  • 18
  • 31
  • Maybe you should checkout these for testing with DRF http://www.django-rest-framework.org/api-guide/testing/#authenticating http://www.django-rest-framework.org/api-guide/testing/#forcing-authentication – Umair Mohammad Jun 04 '18 at 10:52

1 Answers1

25

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)
neverwalkaloner
  • 46,181
  • 7
  • 92
  • 100