Invalid_client or unsupported_grant_type in djnago testcases
This is my code which is a simple signup and login and I'm trying to login via oauth2
class UserAuthTests(TestCase):
def setUp(self):
self.client = APIClient()
self.user = CustomUser.objects.create_user(
username='test',
password='strongpassword123',
email='test@example.com'
)
self.application = Application.objects.create(
name="Test Application",
client_type=Application.CLIENT_CONFIDENTIAL,
authorization_grant_type=Application.GRANT_PASSWORD,
skip_authorization=True,
user=self.user, # Associate the application with the user
)
self.application.save()
def test_register_user(self):
url = '/api/users/register/'
data = {
'username': 'newuser',
'password': 'newpassword123',
'email': 'newuser@example.com'
}
response = self.client.post(url, data, format='json')
print(response.data)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(response.json()['username'], 'newuser')
def test_login_user(self):
url = '/o/token/'
data = {
'grant_type': 'client_credentials', # i've tried with 'password' as well
'username': 'test',
'password': 'strongpassword123',
'client_id': self.application.client_id,
'client_secret': self.application.client_secret,
}
print(self.application.authorization_grant_type == 'password')
print(f"Request Data: {data}")
response = self.client.post(url, data=data, content_type="application/x-www-form-urlencoded")
print(f"Response JSON: {response.json()}")
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertIn('access_token', response.json())
self.assertIn('refresh_token', response.json())
I'm getting Response JSON: {'error': 'unsupported_grant_type'}
or Invalid Client
, my settings file looks like this -
OAUTH2_PROVIDER = {
'ACCESS_TOKEN_EXPIRE_SECONDS': 36000, # Set token expiration
'OAUTH2_BACKEND_CLASS': 'oauth2_provider.oauth2_backends.OAuthLibCore',
}
I have tried changing content_type, but it has not worked. Please let me know how I can fix this.
In my postman, I've tried the same and it works, here is the curl -
curl --location 'localhost:8000/o/token/' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'grant_type=password' \
--data-urlencode 'username=test' \
--data-urlencode 'password=strongpassword123' \
--data-urlencode 'client_id=Q0hvMw2Mk7uv5U4q8LMIOiK9Jo7SpJeXuFbXzaUW' \
--data-urlencode 'client_secret=nUgC6P1OAs6g2qGhS8yPzhh5uenHDVGQBHxM1uGcng3vym5v8vxcEqU6glnfR7XMOURt41k5zDx3pSK0r8HTH5l1VLIaDPMBiY6pjijhoVPjR1N7sLgk1TZxN0zZShaJ'