Report this

What is the reason for this report?

django-oauth-toolkit tutorial error

Posted on March 15, 2020
Alex Won

By Alex Won

Web developer

I tried to add outh2 to my django app, so I used django oauth toolkit. So I followed the tutorial, but if I try to get the users token it always sends me a unsupported_grant_type error. How can I fix this error?

settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'oauth2_provider',
    'rest_framework',
]

OAUTH2_PROVIDER = {
    # parses OAuth2 data from application/json requests
    'OAUTH2_BACKEND_CLASS': 'oauth2_provider.oauth2_backends.JSONOAuthLibCore',
    # this is the list of available scopes
    'SCOPES': {'read': 'Read scope', 'write': 'Write scope', 'groups': 'Access to your groups'}
}

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    )
}

urls.py

urlpatterns = [
    path('admin/', admin.site.urls),
    path('o/', include('oauth2_provider.urls', namespace='oauth2_provider')),
    path('users/', UserList.as_view()),
    path('users/<pk>/', UserDetails.as_view()),
    path('groups/', GroupList.as_view()),
    # ...
]

requirements.txt

Or is there a problem with the versions?

asgiref==3.2.5
autopep8==1.5
certifi==2019.11.28
chardet==3.0.4
Django==3.0.4
django-oauth-toolkit==1.3.0
djangorestframework==3.11.0
idna==2.9
oauthlib==3.1.0
pycodestyle==2.5.0
pytz==2019.3
requests==2.23.0
sqlparse==0.3.1
urllib3==1.25.8
curl -X POST -d "grant_type=password&username=alex&password=alex123" -u"blXarYtbj4uSoZ5AFFmujOdhunGnAKoEU5r749ZE:CdtGEPLxaB225X7OXFmsRSVGQeVLZq1szRLTSmVA8Qr3Ft7DHiXKw9fASBQn7EA9M7IGrJ5xwUty2tI7aoTRuHFsjvcWX6juJu42U4saFY2Uavts9UTvZp8J6drnoCGK" http://localhost:8000/o/token/


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Hello,

The unsupported_grant_type error you’re seeing is usually related to the OAuth 2.0 grant type you’re attempting to use not being supported by the application. The OAuth 2.0 framework defines four grant types: authorization code, implicit, password, and client credentials.

It appears that you’re attempting to use the password grant type in your cURL command (grant_type=password). This is considered a highly trusted type and isn’t recommended for third-party applications.

When you register your application with the provider (in the Django admin interface, in your case), you have to specify which grant types your application will use. Please ensure you have chosen the password grant type during application registration.

The curl command to get the token should be as follows:

curl -X POST -d "grant_type=password&username=<username>&password=<password>&scope=read write" -u"<client_id>:<client_secret>" http://localhost:8000/o/token/

Also, you can add this to your settings.py:

OAUTH2_PROVIDER = {
    ...
    'OAUTH2_VALIDATOR_CLASS': 'oauth2_provider.oauth2_validators.OAuth2Validator',
    ...
}

This sets OAuth2Validator as the validator class, which includes the password grant type.

However, as a safer alternative, consider using the authorization code grant type which is more common and recommended for most situations.

Best,

Bobby

Heya,

The unsupported_grant_type error usually occurs when the grant type specified in your request is not supported or improperly configured. In your case, you are using the password grant type. Here are steps to resolve the issue:

1. Enable password Grant Type

Ensure you have enabled the password grant type in your django-oauth-toolkit configuration. By default, django-oauth-toolkit does not enable it.

Add this to your settings.py:

OAUTH2_PROVIDER = {
    'ACCESS_TOKEN_EXPIRE_SECONDS': 36000,
    'REFRESH_TOKEN_EXPIRE_SECONDS': 1209600,
    'AUTHORIZATION_CODE_EXPIRE_SECONDS': 600,
    'SCOPES': {'read': 'Read scope', 'write': 'Write scope', 'groups': 'Access to your groups'},
    'GRANT_TYPES': ['password', 'authorization_code', 'refresh_token'],
}

2. Check OAuth Application Configuration

Make sure you have created an OAuth application that supports the password grant type.

Run the following commands to create an application:

python manage.py shell
from oauth2_provider.models import Application

Application.objects.create(
    name="YourApp",
    client_type=Application.CLIENT_CONFIDENTIAL,
    authorization_grant_type=Application.GRANT_PASSWORD,
    user=None
)

place "YourApp" with the name of your app.


3. Verify Your POST Request

Ensure your POST request is correctly formatted. Here’s how it should look:

curl -X POST \
  -d "grant_type=password&username=alex&password=alex123" \
  -u "<client_id>:<client_secret>" \
  http://localhost:8000/o/token/

Details

  • Replace <client_id> and <client_secret> with the actual client_id and client_secret of the application you created.
  • Make sure the user (alex) exists in your Django authentication system, and the password is correct.

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.