Django REST Framework JWT

1.19.2 · maintenance · verified Wed Apr 15

drf-jwt (officially `djangorestframework-jwt`) provides JSON Web Token (JWT) based authentication for Django REST framework. This particular fork (version 1.19.2, last released January 2022) offers a basic implementation for token generation, refreshing, and verification. While functional, active development for this specific package is limited, with `djangorestframework-simplejwt` being the widely recommended and actively maintained alternative for modern Django/DRF projects.

Warnings

Install

Imports

Quickstart

Configure `INSTALLED_APPS` and `REST_FRAMEWORK` settings. Add JWT-specific settings under `JWT_AUTH` for token expiration and refresh. Finally, include the `obtain_jwt_token`, `refresh_jwt_token`, and `verify_jwt_token` views in your project's `urls.py`.

import os
from datetime import datetime, timedelta

# settings.py
# Add 'rest_framework' and 'rest_framework_jwt' to INSTALLED_APPS
INSTALLED_APPS = [
    # ...
    'rest_framework',
    'rest_framework_jwt',
    # ...
]

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
}

JWT_AUTH = {
    'JWT_EXPIRATION_DELTA': timedelta(seconds=int(os.environ.get('JWT_EXPIRATION_SECONDS', 3600))),
    'JWT_ALLOW_REFRESH': True,
    'JWT_REFRESH_EXPIRATION_DELTA': timedelta(days=int(os.environ.get('JWT_REFRESH_DAYS', 7))),
    'JWT_RESPONSE_PAYLOAD_HANDLER': 'your_app.utils.jwt_response_payload_handler',
    # 'JWT_SECRET_KEY': os.environ.get('DJANGO_SECRET_KEY', 'your_secret_key'), # Uses Django's SECRET_KEY by default
}

# urls.py
from django.urls import path
from rest_framework_jwt.views import obtain_jwt_token, refresh_jwt_token, verify_jwt_token

urlpatterns = [
    path('api-token-auth/', obtain_jwt_token),
    path('api-token-refresh/', refresh_jwt_token),
    path('api-token-verify/', verify_jwt_token),
    # ... other app URLs
]

# Example of a custom payload handler in your_app/utils.py
# def jwt_response_payload_handler(token, user=None, request=None):
#     return {
#         'token': token,
#         'user': user.username,
#         'id': user.id
#     }

view raw JSON →