Django OAuth Toolkit

repository·master·Indexed 25 days ago

https://github.com/django-oauth/django-oauth-toolkit

An 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.

Tokens
35.1K
Snippets
90
Records
176
Agent score
82%

What's inside django-oauth-toolkit

  1. Overview of Django OAuth Toolkit

    master
    Django OAuth Toolkit is an OAuth 2.0 authorization server designed for Django projects. It provides endpoints, models, and logic to issue and manage OAuth2 tokens. It can function as an authorization server or as a resource server to protect Django or Django REST Framework APIs. The toolkit is built on oauthlib to ensure RFC compliance.
  2. Understand OAuth2 terminology in Django OAuth Toolkit

    master

    To effectively use Django OAuth Toolkit, familiarize yourself with these core OAuth2 concepts:

    • Authorization Server: The application that manages and issues tokens and asks resource owners for consensus to let client applications access their data.
    • Resource Server: The application providing access to its own resources through an OAuth2-protected API.
    • Application: Represents a Client on the Authorization server. These are typically created manually by developers.
    • Client: An application authorized to access OAuth2-protected resources on behalf of a resource owner.
    • Resource Owner: The user who owns the data and must grant authorization to third-party applications.
    • Access Token: A short-lived token required to access protected resources.
    • Authorization Code: An intermediary token obtained via the authorization server, used to authenticate the client and facilitate the transmission of the Access Token.
    • Authorization Token: A very short-lived token issued to clients that can be swapped for an access token.
    • Refresh Token: A token that can be swapped for a new access token without repeating the authorization process. It typically has no expiration time.
  3. Override default Django OAuth Toolkit templates

    master

    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.

  4. Customize OIDC responses by overriding OAUTH2_VALIDATOR_CLASS

    master

    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.

    1. Create a validator file (e.g., my_project/oauth_validators.py).
    2. Update 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
    }
  5. Control authorization form prompts

    master

    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.

  6. Protect Django views using OAuth2 tokens

    master

    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/secret
  7. Schedule the clear_tokens task in Django Admin

    master

    Once django_celery_beat is installed, you can schedule the clear_tokens task via the Django Admin interface:

    1. Create an Interval: Go to django_celery_beat/intervalschedule/, click Add Interval, set your desired frequency (e.g., 10 seconds), and save.
    2. Create a Periodic Task: Go to 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.
  8. Automate token cleanup with Celery

    master
    To prevent the database from becoming cluttered with expired tokens, you can automate the 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.
  9. Clean up expired tokens with cleartokens

    master

    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 tokens idle longer than REFRESH_TOKEN_EXPIRE_SECONDS.
    • Revoked refresh tokens that have exceeded the REFRESH_TOKEN_GRACE_PERIOD_SECONDS grace period.
    • Orphaned refresh tokens (non-revoked tokens whose access tokens were deleted out of band).
    • Expired access and ID tokens.

    Important Notes:

    • If 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.
    • To prevent high CPU/RAM usage during large deletions, tune the process speed using CLEAR_EXPIRED_TOKENS_BATCH_SIZE and CLEAR_EXPIRED_TOKENS_BATCH_INTERVAL settings.
  10. Enable Django OAuth Toolkit in the Django admin

    master

    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:

    • Applications: Registered OAuth clients.
    • Access tokens: Tokens used to call protected APIs.
    • Refresh tokens: Tokens used to obtain new access tokens.
    • Grants: Short-lived authorization codes.
    • ID tokens: OpenID Connect ID tokens (if OIDC is enabled).
    from django.contrib import admin
    from django.urls import path
    
    urlpatterns = [
        path("admin/", admin.site.urls),
        # ...
    ]