OAuth2 Provider for Django web applications with complete server functionality, token management, and authorization endpoints.
npx @tessl/cli install tessl/pypi-django-oauth-toolkit@3.0.0Django 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.
pip install django-oauth-toolkitimport oauth2_provider
from oauth2_provider.models import Application, AccessToken, RefreshToken
from oauth2_provider.decorators import protected_resource, rw_protected_resourceFor Django REST Framework integration:
from oauth2_provider.contrib.rest_framework import OAuth2Authentication, TokenHasScopeFor views and URL patterns:
from oauth2_provider import views
from oauth2_provider import urls # Contains urlpatternsFor 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# 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
}# 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
]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'
})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,
)Django OAuth Toolkit follows the OAuth2 specification (RFC 6749) and OpenID Connect standards, implementing:
The library is built on top of OAuthLib ensuring RFC-compliant OAuth2 implementation and supports multiple Django and Python versions for maximum compatibility.
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: ...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): ...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): ...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): ...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): ...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): ...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 settingDjango 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: ...Django OAuth Toolkit provides comprehensive error handling following OAuth2 and OIDC specifications:
All errors include proper HTTP status codes and error descriptions following RFC specifications.