JSON Web Token based authentication for Django REST framework
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
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.
pip install djangorestframework-jwtINSTALLED_APPS and REST_FRAMEWORK settingsfrom rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework_jwt.views import obtain_jwt_token, refresh_jwt_token, verify_jwt_tokenFor utilities and configuration:
from rest_framework_jwt.utils import jwt_payload_handler, jwt_encode_handler, jwt_decode_handler
from rest_framework_jwt.settings import api_settings# In Django settings.py
INSTALLED_APPS = [
# ... other apps
'rest_framework',
'rest_framework_jwt',
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
],
}
# In urls.py
from rest_framework_jwt.views import obtain_jwt_token, refresh_jwt_token
urlpatterns = [
path('api-token-auth/', obtain_jwt_token),
path('api-token-refresh/', refresh_jwt_token),
]
# Client-side token usage
import requests
# Obtain token
response = requests.post('http://example.com/api-token-auth/', {
'username': 'user@example.com',
'password': 'password123'
})
token = response.json()['token']
# Use token for authenticated requests
headers = {'Authorization': f'JWT {token}'}
response = requests.get('http://example.com/api/protected/', headers=headers)The JWT authentication system is built around these core components:
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.
Core authentication backend classes that integrate with Django REST Framework's authentication system to validate JWTs and authenticate users.
class BaseJSONWebTokenAuthentication(BaseAuthentication):
def authenticate(self, request): ...
def authenticate_credentials(self, payload): ...
def get_jwt_value(self, request): ...
class JSONWebTokenAuthentication(BaseJSONWebTokenAuthentication):
def get_jwt_value(self, request): ...
def authenticate_header(self, request): ...Essential functions for JWT token creation, validation, and payload management, including encoding/decoding handlers and customizable payload processing.
def jwt_payload_handler(user): ...
def jwt_encode_handler(payload): ...
def jwt_decode_handler(token): ...
def jwt_get_secret_key(payload=None): ...
def jwt_get_username_from_payload_handler(payload): ...
def jwt_get_user_id_from_payload_handler(payload): ... # deprecated
def jwt_response_payload_handler(token, user=None, request=None): ...Ready-to-use API views for JWT token operations including token generation, verification, and refresh functionality.
class JSONWebTokenAPIView(APIView): ...
class ObtainJSONWebToken(JSONWebTokenAPIView): ...
class VerifyJSONWebToken(JSONWebTokenAPIView): ...
class RefreshJSONWebToken(JSONWebTokenAPIView): ...
# Function-based views
obtain_jwt_token: callable
refresh_jwt_token: callable
verify_jwt_token: callableValidation and processing classes for JWT authentication workflows, handling user credentials, token verification, and refresh operations.
class JSONWebTokenSerializer(Serializer):
def validate(self, attrs): ...
class VerificationBaseSerializer(Serializer):
def validate(self, attrs): ...
def _check_payload(self, token): ...
def _check_user(self, payload): ...
class VerifyJSONWebTokenSerializer(VerificationBaseSerializer):
def validate(self, attrs): ...
class RefreshJSONWebTokenSerializer(VerificationBaseSerializer):
def validate(self, attrs): ...Comprehensive configuration system for customizing JWT behavior including token expiration, algorithms, secret keys, and handler functions.
# Access configuration
from rest_framework_jwt.settings import api_settings
# Key configuration settings
api_settings.JWT_SECRET_KEY: str
api_settings.JWT_ALGORITHM: str
api_settings.JWT_EXPIRATION_DELTA: timedelta
api_settings.JWT_ALLOW_REFRESH: bool
api_settings.JWT_AUTH_HEADER_PREFIX: strHelper functions and classes for cross-version compatibility and Django integration, including user model handling and field utilities.
def get_username_field(): ...
def get_username(user): ...
class PasswordField(CharField): ...
class Serializer(serializers.Serializer): ...# Django/DRF Types (from framework)
from django.contrib.auth.models import AbstractUser
from rest_framework.authentication import BaseAuthentication
from rest_framework.serializers import Serializer as BaseSerializer
from rest_framework.views import APIView
from rest_framework.request import Request
from rest_framework.response import Response
# JWT Payload Structure
JWTPayload = Dict[str, Any] # Contains user_id, username, exp, etc.
# Configuration Types
JWTSettings = APISettings # From rest_framework.settings
# Handler Function Types
PayloadHandler = Callable[[AbstractUser], JWTPayload]
EncodeHandler = Callable[[JWTPayload], str]
DecodeHandler = Callable[[str], JWTPayload]
ResponseHandler = Callable[[str, Optional[AbstractUser], Optional[Request]], Dict[str, Any]]