Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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">
like image 357
Sudheer K Avatar asked Jun 04 '18 10:06

Sudheer K


1 Answers

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)
like image 70
neverwalkaloner Avatar answered Oct 14 '22 18:10

neverwalkaloner