0

I'm using django rest framework for exposing an api and django oauth toolkit for authentication. So after writing a custom ModelBackend and relevant unit tests, I was trying to write some integration tests too, to verify the endpoint using this backend is returning an access token for some scenarios..

I'm using drf APIClient for making test requests and works great for everything else, but in this I case I'm getting {"error": "unsupported_grant_type"} when I do:

from requests.auth import _basic_auth_str
from rest_framework.test import APIClient


client = APIClient()
client.credentials(HTTP_AUTHORIZATION=_basic_auth_str(CLIENT_ID, CLIENT_SECRET))
client.post(
    '/oauth2/token/', 
    {'grant_type': 'password', 'username': 'user1', 'password': 'pass1'},
    content_type='application/x-www-form-urlencoded'
)

Any ideas?

1 Answer 1

2

I got it to work. I was not encoding the payload. Here is the full working code with example asserts:

import urllib
from requests.auth import _basic_auth_str
from rest_framework.test import APIClient


client = APIClient()

url = reverse('access_token')  
data = urllib.urlencode({
    'client_id': client_id,
    'client_secret': client_secret,
    'grant_type': grant_type
})
response = self.client.post(url, data, 
                            content_type='application/x-www-form-urlencoded',
                            HTTP_AUTHORIZATION=_basic_auth_str(self.client_id, self.client_secret)
                            )    
self.assertEqual(response.status_code, 200)
self.assertIn('access_token', json.loads(response.content))

...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.