0
# Authentication Classes
1
2
JWT authentication backend classes that integrate with Django REST Framework's authentication system to validate JWTs and authenticate users from HTTP requests.
3
4
## Capabilities
5
6
### Base JWT Authentication
7
8
Abstract base class providing core JWT authentication logic that can be extended for different JWT extraction methods.
9
10
```python { .api }
11
class BaseJSONWebTokenAuthentication(BaseAuthentication):
12
def authenticate(self, request):
13
"""
14
Returns a two-tuple of (User, token) if valid JWT authentication
15
is provided, otherwise returns None.
16
17
Args:
18
request: HTTP request object
19
20
Returns:
21
tuple: (User instance, JWT token string) or None
22
23
Raises:
24
AuthenticationFailed: For expired, invalid, or malformed tokens
25
"""
26
27
def authenticate_credentials(self, payload):
28
"""
29
Returns an active user that matches the payload's username.
30
31
Args:
32
payload (dict): Decoded JWT payload containing user information
33
34
Returns:
35
User: Active user instance
36
37
Raises:
38
AuthenticationFailed: If user not found, inactive, or invalid payload
39
"""
40
41
def get_jwt_value(self, request):
42
"""
43
Extract JWT value from request. Base implementation returns None.
44
Must be overridden by subclasses to provide actual token extraction.
45
46
Args:
47
request: HTTP request object
48
49
Returns:
50
str: JWT token string or None if not found
51
52
Note:
53
Base implementation returns None. Subclasses must override this
54
method to implement specific token extraction logic.
55
"""
56
```
57
58
### Standard JWT Authentication
59
60
Complete JWT authentication implementation that extracts tokens from Authorization headers or cookies.
61
62
```python { .api }
63
class JSONWebTokenAuthentication(BaseJSONWebTokenAuthentication):
64
www_authenticate_realm = 'api'
65
66
def get_jwt_value(self, request):
67
"""
68
Extracts JWT from Authorization header or cookie.
69
70
Header format: 'Authorization: JWT <token>'
71
Cookie: Configurable via JWT_AUTH_COOKIE setting
72
73
Args:
74
request: HTTP request object
75
76
Returns:
77
str: JWT token string or None if not found
78
79
Raises:
80
AuthenticationFailed: For malformed Authorization headers
81
"""
82
83
def authenticate_header(self, request):
84
"""
85
Returns WWW-Authenticate header value for 401 responses.
86
87
Args:
88
request: HTTP request object
89
90
Returns:
91
str: WWW-Authenticate header value
92
"""
93
```
94
95
## Usage Examples
96
97
### Basic Authentication Setup
98
99
```python
100
# In Django settings.py
101
REST_FRAMEWORK = {
102
'DEFAULT_AUTHENTICATION_CLASSES': [
103
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
104
],
105
}
106
107
# Optional: Configure JWT settings
108
JWT_AUTH = {
109
'JWT_AUTH_HEADER_PREFIX': 'Bearer', # Change from default 'JWT'
110
'JWT_AUTH_COOKIE': 'jwt-token', # Enable cookie-based auth
111
}
112
```
113
114
### Custom Authentication Class
115
116
```python
117
from rest_framework_jwt.authentication import BaseJSONWebTokenAuthentication
118
119
class CustomJWTAuthentication(BaseJSONWebTokenAuthentication):
120
def get_jwt_value(self, request):
121
# Extract JWT from custom header
122
return request.META.get('HTTP_X_JWT_TOKEN')
123
124
def authenticate_credentials(self, payload):
125
# Add custom user validation logic
126
user = super().authenticate_credentials(payload)
127
128
# Additional checks
129
if not user.profile.is_api_enabled:
130
raise AuthenticationFailed('API access disabled')
131
132
return user
133
```
134
135
### View-Level Authentication
136
137
```python
138
from rest_framework.views import APIView
139
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
140
141
class ProtectedView(APIView):
142
authentication_classes = [JSONWebTokenAuthentication]
143
144
def get(self, request):
145
# request.user is authenticated via JWT
146
return Response({'user': request.user.username})
147
```
148
149
## Error Handling
150
151
The authentication classes raise `AuthenticationFailed` exceptions for various error conditions:
152
153
```python
154
from rest_framework.exceptions import AuthenticationFailed
155
156
# Common authentication errors:
157
# - "Signature has expired" (jwt.ExpiredSignature)
158
# - "Error decoding signature" (jwt.DecodeError)
159
# - "Invalid payload" (missing/invalid username)
160
# - "Invalid signature" (user not found)
161
# - "User account is disabled" (inactive user)
162
# - "Invalid Authorization header" (malformed header format)
163
```
164
165
These exceptions are automatically converted to HTTP 401 Unauthorized responses by Django REST Framework.
166
167
## Module Variables
168
169
The authentication module defines handler function references used by authentication classes:
170
171
```python { .api }
172
jwt_decode_handler = api_settings.JWT_DECODE_HANDLER
173
"""Function reference for decoding JWT tokens."""
174
175
jwt_get_username_from_payload = api_settings.JWT_PAYLOAD_GET_USERNAME_HANDLER
176
"""Function reference for extracting username from JWT payload."""
177
```
178
179
## Integration with DRF
180
181
The authentication classes integrate seamlessly with Django REST Framework's authentication pipeline:
182
183
1. **Request Processing**: DRF calls `authenticate()` method for each configured authentication class
184
2. **User Assignment**: If authentication succeeds, `request.user` and `request.auth` are set
185
3. **Permission Checking**: DRF then processes permission classes with authenticated user
186
4. **Error Handling**: Authentication failures trigger appropriate HTTP responses
187
188
## Configuration Dependencies
189
190
The authentication classes rely on settings from `rest_framework_jwt.settings`:
191
192
- `JWT_DECODE_HANDLER`: Function to decode JWT tokens
193
- `JWT_PAYLOAD_GET_USERNAME_HANDLER`: Function to extract username from payload
194
- `JWT_AUTH_HEADER_PREFIX`: Prefix for Authorization header (default: 'JWT')
195
- `JWT_AUTH_COOKIE`: Cookie name for token storage (optional)