or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

authentication.mdcompatibility.mdconfiguration.mdindex.mdjwt-utilities.mdserializers.mdviews-endpoints.md
tile.json

tessl/pypi-djangorestframework-jwt

JSON Web Token based authentication for Django REST framework

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/djangorestframework-jwt@1.11.x

To install, run

npx @tessl/cli install tessl/pypi-djangorestframework-jwt@1.11.0

index.mddocs/

Django REST Framework JWT

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.

Package Information

  • Package Name: djangorestframework-jwt
  • Language: Python
  • Installation: pip install djangorestframework-jwt
  • Django REST Framework Integration: Add to INSTALLED_APPS and REST_FRAMEWORK settings

Core Imports

from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework_jwt.views import obtain_jwt_token, refresh_jwt_token, verify_jwt_token

For 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

Basic Usage

# 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)

Architecture

The JWT authentication system is built around these core components:

  • Authentication Classes: Handle JWT validation and user authentication for incoming requests
  • Views: Provide API endpoints for token operations (obtain, refresh, verify)
  • Serializers: Validate input data and process authentication logic
  • Utilities: Core JWT encoding/decoding functions and payload handling
  • Settings: Centralized configuration system for JWT behavior

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.

Capabilities

Authentication Classes

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): ...

Authentication

JWT Utilities

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): ...

JWT Utilities

API Views and Endpoints

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: callable

Views and Endpoints

Serializers

Validation 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): ...

Serializers

Configuration and Settings

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: str

Configuration

Compatibility Utilities

Helper 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): ...

Compatibility

Types and Interfaces

# 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]]