Django Rest Framework OAuth2 401

196 views
Skip to first unread message

psychok7

unread,
Sep 8, 2014, 9:21:56 AM9/8/14
to django-res...@googlegroups.com

So i have created a Django Rest Framework using OAuth2 Authentication.

Everything is working fine in the browser (passing the created token and not passing), and it also works fine with

curl -H "Authorization: Bearer 44717e13eabdaf8477d652c2f3e3a049a877245f" http://xxx.herokuapp.com/api/v1/items/?format=json

The problem arises when i try to use the python client where i get a 401 UNAUTHORIZED HTTP ERROR code

i have tried both:

class ApiTest(TestCase):
    def setUp(self):
        self.factory = APIRequestFactory()
        self.client = APIClient()
        self.user = get_user_model().objects.create(username='testuser', email='test...@test.com', password='testing')
        self.url = 'http://xxx.herokuapp.com/api/v1'

    def test_oauth(self):
        self.token = '44717e13eabdaf8477d652c2f3e3a049a877245f'
        header = {'HTTP_AUTHORIZATION': 'Bearer {}'.format(self.token)}
        response = self.client.get(self.url + '/items/', {}, **header)
        print response.status_code

AND

class ApiTest(TestCase):
    def setUp(self):
        self.factory = APIRequestFactory()
        self.client = APIClient()
        self.user = get_user_model().objects.create(username='testuser', email='test...@test.com', password='testing')
        self.url = 'http://xxx.herokuapp.com/api/v1'

    def test_oauth(self):
         self.client.credentials(HTTP_AUTHORIZATION='Bearer 44717e13eabdaf8477d652c2f3e3a049a877245f')
        response = self.client.get(self.url + '/items/', {})
        print response.status_code

This is the request:

(Pdb) response.request
{u'QUERY_STRING': '', 'HTTP_AUTHORIZATION': 'Bearer 44717e13eabdaf8477d652c2f3e3a049a877245f', u'REQUEST_METHOD': 'GET', u'PATH_INFO': '/api/v1/items/'}

Always getting the 401 with the python code. What am i doing wrong??

Timo Piirmann

unread,
Sep 10, 2014, 3:56:56 AM9/10/14
to django-res...@googlegroups.com
This is how test authenticated user accessing url's:

self.user = User.objects.create_user('john', 'jo...@gmail.com', 'johnpassword')
self.client.login(username='john', password='johnpassword')
response = self.client.get(self.url)


Reply all
Reply to author
Forward
0 new messages