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.00
# Django OAuth Toolkit
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: django-oauth-toolkit
7
- **Language**: Python
8
- **Installation**: `pip install django-oauth-toolkit`
9
- **Django Version**: Requires Django 4.2+
10
- **Python Version**: Requires Python 3.8+
11
12
## Core Imports
13
14
```python
15
import oauth2_provider
16
from oauth2_provider.models import Application, AccessToken, RefreshToken
17
from oauth2_provider.decorators import protected_resource, rw_protected_resource
18
```
19
20
For Django REST Framework integration:
21
22
```python
23
from oauth2_provider.contrib.rest_framework import OAuth2Authentication, TokenHasScope
24
```
25
26
For views and URL patterns:
27
28
```python
29
from oauth2_provider import views
30
from oauth2_provider import urls # Contains urlpatterns
31
```
32
33
For application and token management model helpers:
34
35
```python
36
from oauth2_provider.models import (
37
get_application_model, get_access_token_model,
38
get_refresh_token_model, get_grant_model, get_id_token_model
39
)
40
```
41
42
For utilities:
43
44
```python
45
from oauth2_provider.generators import generate_client_id, generate_client_secret
46
```
47
48
## Basic Usage
49
50
### 1. Django Settings Configuration
51
52
```python
53
# settings.py
54
INSTALLED_APPS = [
55
'django.contrib.admin',
56
'django.contrib.auth',
57
'django.contrib.contenttypes',
58
'django.contrib.sessions',
59
'django.contrib.messages',
60
'oauth2_provider',
61
# ... your apps
62
]
63
64
MIDDLEWARE = [
65
# ... other middleware
66
'oauth2_provider.middleware.OAuth2TokenMiddleware',
67
# ... remaining middleware
68
]
69
70
# OAuth2 settings
71
OAUTH2_PROVIDER = {
72
'SCOPES': {
73
'read': 'Read scope',
74
'write': 'Write scope',
75
},
76
'ACCESS_TOKEN_EXPIRE_SECONDS': 3600,
77
'REFRESH_TOKEN_EXPIRE_SECONDS': 3600 * 24 * 7, # 1 week
78
}
79
```
80
81
### 2. URL Configuration
82
83
```python
84
# urls.py
85
from django.contrib import admin
86
from django.urls import path, include
87
88
urlpatterns = [
89
path('admin/', admin.site.urls),
90
path('o/', include('oauth2_provider.urls', namespace='oauth2_provider')),
91
# ... your URLs
92
]
93
```
94
95
### 3. Protecting Views
96
97
```python
98
from oauth2_provider.decorators import protected_resource
99
from django.http import JsonResponse
100
101
@protected_resource(scopes=['read'])
102
def api_endpoint(request):
103
return JsonResponse({
104
'message': 'Hello, OAuth2 world!',
105
'user': request.resource_owner.username if request.resource_owner else 'Anonymous'
106
})
107
```
108
109
### 4. Creating Applications Programmatically
110
111
```python
112
from oauth2_provider.models import Application
113
114
# Create a confidential application
115
application = Application.objects.create(
116
name="My Web Application",
117
user=None, # or assign to a specific user
118
client_type=Application.CLIENT_CONFIDENTIAL,
119
authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE,
120
)
121
```
122
123
## Architecture
124
125
Django OAuth Toolkit follows the OAuth2 specification (RFC 6749) and OpenID Connect standards, implementing:
126
127
- **OAuth2 Authorization Server**: Complete implementation with all standard grant types
128
- **Django Model Integration**: Seamless integration with Django's ORM and admin interface
129
- **Token Management**: Comprehensive token lifecycle management with expiration and revocation
130
- **Scope-based Authorization**: Fine-grained permission control through OAuth2 scopes
131
- **OIDC Support**: OpenID Connect 1.0 implementation for identity layer
132
- **REST Framework Integration**: First-class support for Django REST Framework APIs
133
134
The library is built on top of OAuthLib ensuring RFC-compliant OAuth2 implementation and supports multiple Django and Python versions for maximum compatibility.
135
136
## Capabilities
137
138
### OAuth2 Models and Database Management
139
140
Core Django models for OAuth2 entities including applications, tokens, grants, and OIDC ID tokens. Provides complete ORM integration with validation, relationships, and admin interfaces.
141
142
```python { .api }
143
class Application(AbstractApplication):
144
objects = ApplicationManager()
145
def redirect_uri_allowed(self, uri) -> bool: ...
146
def allows_grant_type(self, *grant_types) -> bool: ...
147
148
class AccessToken(AbstractAccessToken):
149
def is_valid(self, scopes=None) -> bool: ...
150
def allow_scopes(self, scopes) -> bool: ...
151
def revoke(self) -> None: ...
152
153
class RefreshToken(AbstractRefreshToken):
154
def revoke(self) -> None: ...
155
```
156
157
[OAuth2 Models](./models.md)
158
159
### View Protection and Decorators
160
161
Decorators and middleware for protecting Django views with OAuth2 authentication and scope-based authorization. Provides both function decorators and class-based view integration.
162
163
```python { .api }
164
def protected_resource(scopes=None, validator_cls=OAuth2Validator, server_cls=Server): ...
165
def rw_protected_resource(scopes=None, validator_cls=OAuth2Validator, server_cls=Server): ...
166
```
167
168
[View Protection](./view-protection.md)
169
170
### OAuth2 Authorization and Token Endpoints
171
172
Complete OAuth2 server endpoints including authorization, token issuance, token revocation, and introspection. Handles all standard OAuth2 flows and grant types.
173
174
```python { .api }
175
class AuthorizationView(BaseAuthorizationView): ...
176
class TokenView(BaseTokenView): ...
177
class RevokeTokenView(BaseRevokeTokenView): ...
178
class IntrospectTokenView(BaseIntrospectTokenView): ...
179
```
180
181
[OAuth2 Endpoints](./oauth2-endpoints.md)
182
183
### Application and Token Management Views
184
185
Web interface views for managing OAuth2 applications and user-authorized tokens. Provides complete CRUD operations with Django's class-based views.
186
187
```python { .api }
188
class ApplicationList(ListView): ...
189
class ApplicationDetail(DetailView): ...
190
class ApplicationRegistration(CreateView): ...
191
class ApplicationUpdate(UpdateView): ...
192
class ApplicationDelete(DeleteView): ...
193
```
194
195
[Management Views](./management-views.md)
196
197
### OpenID Connect (OIDC) Support
198
199
OpenID Connect 1.0 implementation providing identity layer on top of OAuth2. Includes discovery, UserInfo, JWKS, and logout endpoints with JWT ID token support.
200
201
```python { .api }
202
class ConnectDiscoveryInfoView(View): ...
203
class UserInfoView(View): ...
204
class JwksInfoView(View): ...
205
class RPInitiatedLogoutView(View): ...
206
```
207
208
[OpenID Connect](./oidc.md)
209
210
### Django REST Framework Integration
211
212
Complete Django REST Framework integration with OAuth2 authentication and permission classes. Provides token-based API authentication with scope validation.
213
214
```python { .api }
215
class OAuth2Authentication(BaseAuthentication): ...
216
class TokenHasScope(BasePermission): ...
217
class TokenHasReadWriteScope(BasePermission): ...
218
class IsAuthenticatedOrTokenHasScope(BasePermission): ...
219
```
220
221
[DRF Integration](./drf-integration.md)
222
223
### Settings and Configuration
224
225
Comprehensive configuration system for customizing OAuth2 behavior, token lifetimes, algorithms, and backend classes. Supports Django settings integration with validation.
226
227
```python { .api }
228
oauth2_settings: OAuth2ProviderSettings
229
OAUTH2_PROVIDER: Dict[str, Any] # Django setting
230
```
231
232
[Settings](./settings.md)
233
234
### Management Commands and Utilities
235
236
Django management commands for OAuth2 administration including token cleanup and application creation. Includes utility functions for JWT handling and validation.
237
238
```python { .api }
239
def clear_expired() -> None: ...
240
def generate_client_id() -> str: ...
241
def generate_client_secret() -> str: ...
242
```
243
244
[Management Commands](./management-commands.md)
245
246
## Error Handling
247
248
Django OAuth Toolkit provides comprehensive error handling following OAuth2 and OIDC specifications:
249
250
- **OAuthToolkitError**: Base class for OAuth2 errors with OAuthLib integration
251
- **FatalClientError**: Critical OAuth2 errors requiring immediate attention
252
- **OIDCError**: Base class for OpenID Connect specific errors
253
- **Validation Errors**: Django form and model validation for OAuth2 entities
254
255
All errors include proper HTTP status codes and error descriptions following RFC specifications.