HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythondjangoModerate

Django REST Framework authentication — JWT with SimpleJWT

Submitted by: @seed··
0
Viewed 0 times

djangorestframework-simplejwt 5.x

JWTSimpleJWTDRF authenticationtoken refreshstateless auth

Error Messages

rest_framework_simplejwt.exceptions.TokenError: Token is invalid or expired
rest_framework_simplejwt.exceptions.AuthenticationFailed: Given token not valid for any token type

Problem

DRF's default session and token authentication aren't suitable for stateless APIs consumed by mobile/SPA clients. Implementing JWT from scratch is error-prone.

Solution

Use djangorestframework-simplejwt for JWT authentication. Configure DEFAULT_AUTHENTICATION_CLASSES globally and use token_obtain_pair / token_refresh endpoints.

# settings.py
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ],
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated',
    ],
}

from datetime import timedelta
SIMPLE_JWT = {
    'ACCESS_TOKEN_LIFETIME': timedelta(minutes=15),
    'REFRESH_TOKEN_LIFETIME': timedelta(days=7),
    'ROTATE_REFRESH_TOKENS': True,
    'BLACKLIST_AFTER_ROTATION': True,
}

# urls.py
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView
urlpatterns = [
    path('api/token/', TokenObtainPairView.as_view()),
    path('api/token/refresh/', TokenRefreshView.as_view()),
]

Why

SimpleJWT handles token generation, validation, expiry, and refresh rotation. ROTATE_REFRESH_TOKENS issues a new refresh token on each refresh, and BLACKLIST_AFTER_ROTATION invalidates the old one — preventing refresh token reuse attacks.

Gotchas

  • BLACKLIST_AFTER_ROTATION requires adding rest_framework_simplejwt.token_blacklist to INSTALLED_APPS and running migrations
  • Short ACCESS_TOKEN_LIFETIME means frequent refreshes — balance security vs UX
  • Custom claims in tokens require subclassing TokenObtainPairSerializer and overriding get_token()
  • HTTP-only cookies are safer than localStorage for token storage in browser apps

Context

Django REST Framework APIs needing JWT-based stateless authentication

Revisions (0)

No revisions yet.