JSON Web Token for Django REST Framework

1.11.0 · maintenance · verified Thu Apr 16

djangorestframework-jwt provides JSON Web Token (JWT) based authentication for Django REST Framework. While historically popular, the library is largely unmaintained with its last release (1.11.0) in October 2017. Users are generally recommended to migrate to more actively maintained alternatives like `drf-simplejwt` for current Django and DRF versions, as this library lacks recent security updates and compatibility testing with newer Django/DRF releases.

Common errors

Warnings

Install

Imports

Quickstart

Configure `settings.py` by adding `rest_framework_jwt` to `INSTALLED_APPS`, setting `DEFAULT_AUTHENTICATION_CLASSES` for DRF, and defining `JWT_AUTH` settings, especially `JWT_SECRET_KEY`. Then, add the token authentication URLs to your project's `urls.py`.

import os
import datetime

# settings.py
INSTALLED_APPS = [
    # ... other apps
    'rest_framework',
    'rest_framework_jwt',
]

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
        # 'rest_framework.authentication.SessionAuthentication', # Optional
        # 'rest_framework.authentication.BasicAuthentication', # Optional
    ),
}

JWT_AUTH = {
    'JWT_RESPONSE_PAYLOAD_HANDLER': 'your_project_name.utils.jwt_response_payload_handler', # Customize response data
    'JWT_SECRET_KEY': os.environ.get('DJANGO_SECRET_KEY', 'insecure-dev-secret-key'), # IMPORTANT: Use a strong, unique key from env var in production
    'JWT_ALLOW_REFRESH': True,
    'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=3600), # Token valid for 1 hour
    'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=7), # Refresh token valid for 7 days
    # ... other settings
}

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

urlpatterns = [
    # ... your other urls
    path('api/token/', obtain_jwt_token, name='api_token_auth'),
    path('api/token/refresh/', refresh_jwt_token, name='api_token_refresh'),
    path('api/token/verify/', verify_jwt_token, name='api_token_verify'),
]

view raw JSON →