Overview of Django OAuth Toolkit
masteroauthlib to ensure RFC compliance.repository·master·Indexed 25 days ago
https://github.com/django-oauth/django-oauth-toolkitAn OAuth 2.0 authorization server for Django applications. It provides the models, endpoints, and logic to manage OAuth2 tokens within a Django project and can serve as a resource server to protect Django or Django REST Framework APIs.
oauthlib to ensure RFC compliance.To effectively use Django OAuth Toolkit, familiarize yourself with these core OAuth2 concepts:
cleartokens management command on a schedule to remove expired tokens in bulk.You can customize the look and feel of the OAuth2 provider by overriding its default templates. To do this, create a folder named oauth2_provider inside your project's template directory and add files that match the names of the templates you wish to override.
Requirement: In your settings.py, 'django.contrib.staticfiles' must be listed in INSTALLED_APPS before 'oauth2_provider' to ensure your custom templates are correctly discovered.
To customize OpenID Connect (OIDC) ID tokens, UserInfo responses, or claim discovery, you must create a custom validator class inheriting from oauth2_provider.oauth2_validators.OAuth2Validator and register it in your Django settings.
my_project/oauth_validators.py).settings.py to use the new class via the OAUTH2_PROVIDER dictionary.# my_project/oauth_validators.py
from oauth2_provider.oauth2_validators import OAuth2Validator
class CustomOAuth2Validator(OAuth2Validator):
pass
# settings.py
OAUTH2_PROVIDER = {
"OAUTH2_VALIDATOR_CLASS": "my_project.oauth_validators.CustomOAuth2Validator",
# ... other settings
}You can control whether users are prompted for authorization using the approval_prompt parameter when hitting the authorization endpoint.
Values:
force: Users are always prompted for authorization.auto: Users are prompted only the first time; subsequent authorizations for the same application and scopes are automatically accepted.To completely bypass the authorization form for trusted applications, set skip_authorization = True on the Application model via the Django admin or programmatically.
Once the authentication backend and middleware are configured, you can protect standard Django views using the built-in login_required decorator. The OAuth2 backend will automatically authenticate the user if a valid Bearer token is provided in the Authorization header.
To test the protection, use a curl command with the header: Authorization: Bearer <your_access_token>.
from django.contrib.auth.decorators import login_required
from django.http.response import HttpResponse
@login_required()
def secret_page(request, *args, **kwargs):
return HttpResponse('Secret contents!', status=200)Testing with curl:
curl -H "Authorization: Bearer 123456" -X GET http://localhost:8000/secretOnce django_celery_beat is installed, you can schedule the clear_tokens task via the Django Admin interface:
django_celery_beat/intervalschedule/, click Add Interval, set your desired frequency (e.g., 10 seconds), and save.django_celery_beat/periodictask/, click Add Periodic Task, select your task (e.g., tutorial.tasks.clear_tokens), choose the interval you just created, and save.To enable the OAuth 2.0 authorization server endpoints, include oauth2_provider.urls in your project's urls.py.
from oauth2_provider import urls as oauth2_urls
urlpatterns = [
...
path('o/', include(oauth2_urls)),
]clear_expired maintenance task using Celery and django-celery-beat. This involves setting up a message broker (like RabbitMQ), configuring Celery within your Django app, and defining a periodic task that calls oauth2_provider.models.clear_expired.The cleartokens management command removes expired or unusable tokens from the database to prevent clutter. It should be run regularly (e.g., via cron).
Tokens removed include:
REFRESH_TOKEN_EXPIRE_SECONDS.REFRESH_TOKEN_GRACE_PERIOD_SECONDS grace period.Important Notes:
REFRESH_TOKEN_EXPIRE_SECONDS is unset or 0, the command will only remove revoked and orphaned tokens. Set this value to enable full expiry-based cleanup.CLEAR_EXPIRED_TOKENS_BATCH_SIZE and CLEAR_EXPIRED_TOKENS_BATCH_INTERVAL settings.Django OAuth Toolkit integrates with the standard Django admin site. To enable it, ensure django.contrib.admin is in your INSTALLED_APPS and configured in your urls.py. Once logged in as a staff user, you will see a Django OAuth Toolkit section containing:
from django.contrib import admin
from django.urls import path
urlpatterns = [
path("admin/", admin.site.urls),
# ...
]