0
# Django REST Framework JWT
1
2
JSON Web Token authentication for Django REST Framework, providing secure stateless authentication for web APIs. This package implements JWT-based authentication classes, token generation and validation utilities, custom serializers for authentication endpoints, and configurable settings for token expiration, refresh mechanisms, and payload customization.
3
4
## Package Information
5
6
- **Package Name**: djangorestframework-jwt
7
- **Language**: Python
8
- **Installation**: `pip install djangorestframework-jwt`
9
- **Django REST Framework Integration**: Add to `INSTALLED_APPS` and `REST_FRAMEWORK` settings
10
11
## Core Imports
12
13
```python
14
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
15
from rest_framework_jwt.views import obtain_jwt_token, refresh_jwt_token, verify_jwt_token
16
```
17
18
For utilities and configuration:
19
20
```python
21
from rest_framework_jwt.utils import jwt_payload_handler, jwt_encode_handler, jwt_decode_handler
22
from rest_framework_jwt.settings import api_settings
23
```
24
25
## Basic Usage
26
27
```python
28
# In Django settings.py
29
INSTALLED_APPS = [
30
# ... other apps
31
'rest_framework',
32
'rest_framework_jwt',
33
]
34
35
REST_FRAMEWORK = {
36
'DEFAULT_AUTHENTICATION_CLASSES': [
37
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
38
],
39
}
40
41
# In urls.py
42
from rest_framework_jwt.views import obtain_jwt_token, refresh_jwt_token
43
44
urlpatterns = [
45
path('api-token-auth/', obtain_jwt_token),
46
path('api-token-refresh/', refresh_jwt_token),
47
]
48
49
# Client-side token usage
50
import requests
51
52
# Obtain token
53
response = requests.post('http://example.com/api-token-auth/', {
54
'username': 'user@example.com',
55
'password': 'password123'
56
})
57
token = response.json()['token']
58
59
# Use token for authenticated requests
60
headers = {'Authorization': f'JWT {token}'}
61
response = requests.get('http://example.com/api/protected/', headers=headers)
62
```
63
64
## Architecture
65
66
The JWT authentication system is built around these core components:
67
68
- **Authentication Classes**: Handle JWT validation and user authentication for incoming requests
69
- **Views**: Provide API endpoints for token operations (obtain, refresh, verify)
70
- **Serializers**: Validate input data and process authentication logic
71
- **Utilities**: Core JWT encoding/decoding functions and payload handling
72
- **Settings**: Centralized configuration system for JWT behavior
73
74
This modular design enables flexible JWT authentication that integrates seamlessly with Django REST Framework's authentication pipeline while supporting various token workflows including refresh tokens, cookie-based storage, and custom payload handling.
75
76
## Capabilities
77
78
### Authentication Classes
79
80
Core authentication backend classes that integrate with Django REST Framework's authentication system to validate JWTs and authenticate users.
81
82
```python { .api }
83
class BaseJSONWebTokenAuthentication(BaseAuthentication):
84
def authenticate(self, request): ...
85
def authenticate_credentials(self, payload): ...
86
def get_jwt_value(self, request): ...
87
88
class JSONWebTokenAuthentication(BaseJSONWebTokenAuthentication):
89
def get_jwt_value(self, request): ...
90
def authenticate_header(self, request): ...
91
```
92
93
[Authentication](./authentication.md)
94
95
### JWT Utilities
96
97
Essential functions for JWT token creation, validation, and payload management, including encoding/decoding handlers and customizable payload processing.
98
99
```python { .api }
100
def jwt_payload_handler(user): ...
101
def jwt_encode_handler(payload): ...
102
def jwt_decode_handler(token): ...
103
def jwt_get_secret_key(payload=None): ...
104
def jwt_get_username_from_payload_handler(payload): ...
105
def jwt_get_user_id_from_payload_handler(payload): ... # deprecated
106
def jwt_response_payload_handler(token, user=None, request=None): ...
107
```
108
109
[JWT Utilities](./jwt-utilities.md)
110
111
### API Views and Endpoints
112
113
Ready-to-use API views for JWT token operations including token generation, verification, and refresh functionality.
114
115
```python { .api }
116
class JSONWebTokenAPIView(APIView): ...
117
118
class ObtainJSONWebToken(JSONWebTokenAPIView): ...
119
class VerifyJSONWebToken(JSONWebTokenAPIView): ...
120
class RefreshJSONWebToken(JSONWebTokenAPIView): ...
121
122
# Function-based views
123
obtain_jwt_token: callable
124
refresh_jwt_token: callable
125
verify_jwt_token: callable
126
```
127
128
[Views and Endpoints](./views-endpoints.md)
129
130
### Serializers
131
132
Validation and processing classes for JWT authentication workflows, handling user credentials, token verification, and refresh operations.
133
134
```python { .api }
135
class JSONWebTokenSerializer(Serializer):
136
def validate(self, attrs): ...
137
138
class VerificationBaseSerializer(Serializer):
139
def validate(self, attrs): ...
140
def _check_payload(self, token): ...
141
def _check_user(self, payload): ...
142
143
class VerifyJSONWebTokenSerializer(VerificationBaseSerializer):
144
def validate(self, attrs): ...
145
146
class RefreshJSONWebTokenSerializer(VerificationBaseSerializer):
147
def validate(self, attrs): ...
148
```
149
150
[Serializers](./serializers.md)
151
152
### Configuration and Settings
153
154
Comprehensive configuration system for customizing JWT behavior including token expiration, algorithms, secret keys, and handler functions.
155
156
```python { .api }
157
# Access configuration
158
from rest_framework_jwt.settings import api_settings
159
160
# Key configuration settings
161
api_settings.JWT_SECRET_KEY: str
162
api_settings.JWT_ALGORITHM: str
163
api_settings.JWT_EXPIRATION_DELTA: timedelta
164
api_settings.JWT_ALLOW_REFRESH: bool
165
api_settings.JWT_AUTH_HEADER_PREFIX: str
166
```
167
168
[Configuration](./configuration.md)
169
170
### Compatibility Utilities
171
172
Helper functions and classes for cross-version compatibility and Django integration, including user model handling and field utilities.
173
174
```python { .api }
175
def get_username_field(): ...
176
def get_username(user): ...
177
178
class PasswordField(CharField): ...
179
class Serializer(serializers.Serializer): ...
180
```
181
182
[Compatibility](./compatibility.md)
183
184
## Types and Interfaces
185
186
```python { .api }
187
# Django/DRF Types (from framework)
188
from django.contrib.auth.models import AbstractUser
189
from rest_framework.authentication import BaseAuthentication
190
from rest_framework.serializers import Serializer as BaseSerializer
191
from rest_framework.views import APIView
192
from rest_framework.request import Request
193
from rest_framework.response import Response
194
195
# JWT Payload Structure
196
JWTPayload = Dict[str, Any] # Contains user_id, username, exp, etc.
197
198
# Configuration Types
199
JWTSettings = APISettings # From rest_framework.settings
200
201
# Handler Function Types
202
PayloadHandler = Callable[[AbstractUser], JWTPayload]
203
EncodeHandler = Callable[[JWTPayload], str]
204
DecodeHandler = Callable[[str], JWTPayload]
205
ResponseHandler = Callable[[str, Optional[AbstractUser], Optional[Request]], Dict[str, Any]]
206
```