or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

drf-integration.mdindex.mdmanagement-commands.mdmanagement-views.mdmodels.mdoauth2-endpoints.mdoidc.mdsettings.mdview-protection.md
tile.json

tessl/pypi-django-oauth-toolkit

OAuth2 Provider for Django web applications with complete server functionality, token management, and authorization endpoints.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/django-oauth-toolkit@3.0.x

To install, run

npx @tessl/cli install tessl/pypi-django-oauth-toolkit@3.0.0

index.mddocs/

Django OAuth Toolkit

Django OAuth Toolkit is a comprehensive OAuth2 authentication and authorization provider library for Django web applications. It provides out-of-the-box endpoints, data models, and business logic needed to add complete OAuth2 capabilities to Django projects, including token management, client application registration, and authorization server functionality.

Package Information

  • Package Name: django-oauth-toolkit
  • Language: Python
  • Installation: pip install django-oauth-toolkit
  • Django Version: Requires Django 4.2+
  • Python Version: Requires Python 3.8+

Core Imports

import oauth2_provider
from oauth2_provider.models import Application, AccessToken, RefreshToken
from oauth2_provider.decorators import protected_resource, rw_protected_resource

For Django REST Framework integration:

from oauth2_provider.contrib.rest_framework import OAuth2Authentication, TokenHasScope

For views and URL patterns:

from oauth2_provider import views
from oauth2_provider import urls  # Contains urlpatterns

For application and token management model helpers:

from oauth2_provider.models import (
    get_application_model, get_access_token_model, 
    get_refresh_token_model, get_grant_model, get_id_token_model
)

For utilities:

from oauth2_provider.generators import generate_client_id, generate_client_secret

Basic Usage

1. Django Settings Configuration

# settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'oauth2_provider',
    # ... your apps
]

MIDDLEWARE = [
    # ... other middleware
    'oauth2_provider.middleware.OAuth2TokenMiddleware',
    # ... remaining middleware
]

# OAuth2 settings
OAUTH2_PROVIDER = {
    'SCOPES': {
        'read': 'Read scope',
        'write': 'Write scope',
    },
    'ACCESS_TOKEN_EXPIRE_SECONDS': 3600,
    'REFRESH_TOKEN_EXPIRE_SECONDS': 3600 * 24 * 7,  # 1 week
}

2. URL Configuration

# urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('o/', include('oauth2_provider.urls', namespace='oauth2_provider')),
    # ... your URLs
]

3. Protecting Views

from oauth2_provider.decorators import protected_resource
from django.http import JsonResponse

@protected_resource(scopes=['read'])
def api_endpoint(request):
    return JsonResponse({
        'message': 'Hello, OAuth2 world!',
        'user': request.resource_owner.username if request.resource_owner else 'Anonymous'
    })

4. Creating Applications Programmatically

from oauth2_provider.models import Application

# Create a confidential application
application = Application.objects.create(
    name="My Web Application",
    user=None,  # or assign to a specific user
    client_type=Application.CLIENT_CONFIDENTIAL,
    authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE,
)

Architecture

Django OAuth Toolkit follows the OAuth2 specification (RFC 6749) and OpenID Connect standards, implementing:

  • OAuth2 Authorization Server: Complete implementation with all standard grant types
  • Django Model Integration: Seamless integration with Django's ORM and admin interface
  • Token Management: Comprehensive token lifecycle management with expiration and revocation
  • Scope-based Authorization: Fine-grained permission control through OAuth2 scopes
  • OIDC Support: OpenID Connect 1.0 implementation for identity layer
  • REST Framework Integration: First-class support for Django REST Framework APIs

The library is built on top of OAuthLib ensuring RFC-compliant OAuth2 implementation and supports multiple Django and Python versions for maximum compatibility.

Capabilities

OAuth2 Models and Database Management

Core Django models for OAuth2 entities including applications, tokens, grants, and OIDC ID tokens. Provides complete ORM integration with validation, relationships, and admin interfaces.

class Application(AbstractApplication):
    objects = ApplicationManager()
    def redirect_uri_allowed(self, uri) -> bool: ...
    def allows_grant_type(self, *grant_types) -> bool: ...

class AccessToken(AbstractAccessToken):
    def is_valid(self, scopes=None) -> bool: ...
    def allow_scopes(self, scopes) -> bool: ...
    def revoke(self) -> None: ...

class RefreshToken(AbstractRefreshToken):
    def revoke(self) -> None: ...

OAuth2 Models

View Protection and Decorators

Decorators and middleware for protecting Django views with OAuth2 authentication and scope-based authorization. Provides both function decorators and class-based view integration.

def protected_resource(scopes=None, validator_cls=OAuth2Validator, server_cls=Server): ...
def rw_protected_resource(scopes=None, validator_cls=OAuth2Validator, server_cls=Server): ...

View Protection

OAuth2 Authorization and Token Endpoints

Complete OAuth2 server endpoints including authorization, token issuance, token revocation, and introspection. Handles all standard OAuth2 flows and grant types.

class AuthorizationView(BaseAuthorizationView): ...
class TokenView(BaseTokenView): ...
class RevokeTokenView(BaseRevokeTokenView): ...
class IntrospectTokenView(BaseIntrospectTokenView): ...

OAuth2 Endpoints

Application and Token Management Views

Web interface views for managing OAuth2 applications and user-authorized tokens. Provides complete CRUD operations with Django's class-based views.

class ApplicationList(ListView): ...
class ApplicationDetail(DetailView): ...
class ApplicationRegistration(CreateView): ...
class ApplicationUpdate(UpdateView): ...
class ApplicationDelete(DeleteView): ...

Management Views

OpenID Connect (OIDC) Support

OpenID Connect 1.0 implementation providing identity layer on top of OAuth2. Includes discovery, UserInfo, JWKS, and logout endpoints with JWT ID token support.

class ConnectDiscoveryInfoView(View): ...
class UserInfoView(View): ...
class JwksInfoView(View): ...
class RPInitiatedLogoutView(View): ...

OpenID Connect

Django REST Framework Integration

Complete Django REST Framework integration with OAuth2 authentication and permission classes. Provides token-based API authentication with scope validation.

class OAuth2Authentication(BaseAuthentication): ...
class TokenHasScope(BasePermission): ...
class TokenHasReadWriteScope(BasePermission): ...
class IsAuthenticatedOrTokenHasScope(BasePermission): ...

DRF Integration

Settings and Configuration

Comprehensive configuration system for customizing OAuth2 behavior, token lifetimes, algorithms, and backend classes. Supports Django settings integration with validation.

oauth2_settings: OAuth2ProviderSettings
OAUTH2_PROVIDER: Dict[str, Any]  # Django setting

Settings

Management Commands and Utilities

Django management commands for OAuth2 administration including token cleanup and application creation. Includes utility functions for JWT handling and validation.

def clear_expired() -> None: ...
def generate_client_id() -> str: ...
def generate_client_secret() -> str: ...

Management Commands

Error Handling

Django OAuth Toolkit provides comprehensive error handling following OAuth2 and OIDC specifications:

  • OAuthToolkitError: Base class for OAuth2 errors with OAuthLib integration
  • FatalClientError: Critical OAuth2 errors requiring immediate attention
  • OIDCError: Base class for OpenID Connect specific errors
  • Validation Errors: Django form and model validation for OAuth2 entities

All errors include proper HTTP status codes and error descriptions following RFC specifications.