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

1

15

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">
Dextrogyrate answered 4/6, 2018 at 10:35 Comment(1)
Maybe you should checkout these for testing with DRF django-rest-framework.org/api-guide/testing/#authenticating django-rest-framework.org/api-guide/testing/…Amberly
A
27

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)
Alphabetical answered 4/6, 2018 at 10:41 Comment(3)
I have tried all sorts of combination with headers={} inside client.get() but forgot to try this. I worked. Thank youDextrogyrate
Where is this line placed, before : client.get() ?Gaulish
Am getting this error :ValueError: invalid literal for int() with base 10: 'Gaulish

© 2022 - 2024 — McMap. All rights reserved.