Django REST Framework Simple JWT
djangorestframework-simplejwt is a minimal JSON Web Token (JWT) authentication plugin designed for Django REST Framework. It provides a straightforward way to implement JWT-based authentication, including token obtain, refresh, and verification. Currently at version 5.5.1, it maintains an active development pace with regular updates and patches.
Warnings
- gotcha A missing migration (0013_blacklist) for the `rest_framework_simplejwt.token_blacklist` app was added in v5.5.1. Users who previously ran `makemigrations` on a development branch may have a phantom migration or encounter issues if they created a migration with this name themselves. Carefully review your `django_migrations` table before running `migrate`.
- breaking Version 5.5.0 introduced a cap on the `PyJWT` dependency, requiring `<2.10.0`. This was done to avoid incompatibility with a subject claim type requirement introduced in newer `PyJWT` versions. Users with `PyJWT` 2.10.0 or higher will experience `TypeError` during token validation.
- breaking In version 5.0.0, the default value for `BLACKLIST_AFTER_ROTATION` in `SIMPLE_JWT` settings changed from `True` to `False`. This means refresh tokens are no longer automatically blacklisted after rotation unless explicitly set to `True`.
- gotcha With version 5.3.1, support for End-of-Life (EOL) Python, Django, and Django REST Framework versions was removed. While not a breaking change in the library's API, it signifies that installations on older stacks are no longer officially supported and may encounter unpatched issues or unexpected behavior.
Install
-
pip install djangorestframework-simplejwt
Imports
- JWTAuthentication
from rest_framework_simplejwt.authentication import JWTAuthentication
- TokenObtainPairView
from rest_framework_simplejwt.views import TokenObtainPairView
- TokenRefreshView
from rest_framework_simplejwt.views import TokenRefreshView
- TokenVerifyView
from rest_framework_simplejwt.views import TokenVerifyView
- TokenObtainPairSerializer
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
- RefreshToken
from rest_framework_simplejwt.tokens import RefreshToken
Quickstart
import os
import datetime
from pathlib import Path
# settings.py
SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', 'your-secret-key')
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = [
# ... other Django apps
'rest_framework',
'rest_framework_simplejwt.token_blacklist', # Required for token blacklisting
]
MIDDLEWARE = [
# ...
]
ROOT_URLCONF = 'myproject.urls'
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
),
}
SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': datetime.timedelta(minutes=5),
'REFRESH_TOKEN_LIFETIME': datetime.timedelta(days=1),
'ROTATE_REFRESH_TOKENS': True, # Set to True to enable automatic blacklisting on refresh
'BLACKLIST_AFTER_ROTATION': True,
'UPDATE_LAST_LOGIN': False,
'ALGORITHM': 'HS256',
'SIGNING_KEY': SECRET_KEY,
'VERIFYING_KEY': None,
'AUDIENCE': None,
'ISSUER': None,
'JWK_URL': None,
'LEEWAY': 0,
'AUTH_HEADER_TYPES': ('Bearer',),
'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION',
'USER_ID_FIELD': 'id',
'USER_ID_CLAIM': 'user_id',
'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule',
'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),
'TOKEN_TYPE_CLAIM': 'token_type',
'TOKEN_USER_CLASS': 'rest_framework_simplejwt.models.TokenUser',
'JTI_CLAIM': 'jti',
'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp',
'SLIDING_TOKEN_LIFETIME': datetime.timedelta(minutes=5),
'SLIDING_TOKEN_REFRESH_LIFETIME': datetime.timedelta(days=1),
'TOKEN_OBTAIN_PAIR_SERIALIZER': 'rest_framework_simplejwt.serializers.TokenObtainPairSerializer',
'TOKEN_REFRESH_SERIALIZER': 'rest_framework_simplejwt.serializers.TokenRefreshSerializer',
'TOKEN_VERIFY_SERIALIZER': 'rest_framework_simplejwt.serializers.TokenVerifySerializer',
'TOKEN_BLACKLIST_SERIALIZER': 'rest_framework_simplejwt.serializers.TokenBlacklistSerializer',
'TOKEN_SLIDING_OBTAIN_SERIALIZER': 'rest_framework_simplejwt.serializers.TokenObtainSlidingSerializer',
'TOKEN_SLIDING_REFRESH_SERIALIZER': 'rest_framework_simplejwt.serializers.TokenRefreshSlidingSerializer',
}
# urls.py
from django.urls import path
from rest_framework_simplejwt.views import (
TokenObtainPairView,
TokenRefreshView,
TokenVerifyView,
TokenBlacklistView
)
urlpatterns = [
path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
path('api/token/verify/', TokenVerifyView.as_view(), name='token_verify'),
path('api/token/blacklist/', TokenBlacklistView.as_view(), name='token_blacklist'),
]