Full answer
Flow:
POST /api/token/with credentials returns{"access": "...", "refresh": "..."}(TokenObtainPairView).- The client sends
Authorization: Bearer <access>on API calls.JWTAuthenticationchecks the signature (HS256 withSECRET_KEYby default, or RS256 with a key pair), theexpclaim and the token type, then loads the user by theuser_idclaim. - When the access token expires (default 5 minutes), the client calls
POST /api/token/refresh/with the refresh token (default 1 day) and receives a new access token.
Settings (SIMPLE_JWT): ACCESS_TOKEN_LIFETIME, REFRESH_TOKEN_LIFETIME, ROTATE_REFRESH_TOKENS (issue a new refresh token on refresh), BLACKLIST_AFTER_ROTATION (needs rest_framework_simplejwt.token_blacklist in INSTALLED_APPS and its tables), ALGORITHM, SIGNING_KEY, AUDIENCE, ISSUER, UPDATE_LAST_LOGIN.
Security trade-offs:
- Statelessness: the server does not store access tokens, which scales well, but a stolen or issued token stays valid until expiry. Short lifetimes limit damage; the blacklist (a database table) revokes refresh tokens for logout and rotation reuse detection.
- Storage on the client:
localStorageis readable by any XSS; an HttpOnly, Secure, SameSite cookie is safer against XSS but needs CSRF protection. Single-page apps often keep access tokens in memory and the refresh token in an HttpOnly cookie. - Claims are signed, not encrypted: anyone can read them. Do not put secrets or private data inside.
- Use HTTPS only; rotate signing keys (RS256 with
kidand JWKS is common across services); validateissandaudwhen several services share keys. - Permissions still come from the user record: a deactivated user fails authentication, since the user is loaded on each request (
USER_AUTHENTICATION_RULE). - Compare with sessions: server-side sessions can be revoked instantly and suit browser apps on one domain; JWTs suit mobile clients and cross-service calls.
import sys
import types
from datetime import timedelta
import django
from django.conf import settings
# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__
settings.configure(
SECRET_KEY="demo-only-key-not-for-production",
ALLOWED_HOSTS=["testserver"], # the host name used by Django's test client
ROOT_URLCONF=__name__,
REST_FRAMEWORK={"DEFAULT_AUTHENTICATION_CLASSES": ["rest_framework_simplejwt.authentication.JWTAuthentication"]},
SIMPLE_JWT={"ACCESS_TOKEN_LIFETIME": timedelta(minutes=5), "REFRESH_TOKEN_LIFETIME": timedelta(days=1),
"ROTATE_REFRESH_TOKENS": True},
INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "rest_framework", "rest_framework_simplejwt", "school"],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()
from django.contrib.auth import get_user_model
from django.db import connection
from django.urls import path
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.test import APIClient
from rest_framework.views import APIView
from rest_framework_simplejwt.tokens import AccessToken
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView
User = get_user_model()
with connection.schema_editor() as editor:
editor.create_model(User)
user = User.objects.create_user("asha", password="s3cret-pass")
class Me(APIView):
permission_classes = [IsAuthenticated]
def get(self, request):
return Response({"user": request.user.username})
urlpatterns = [
path("api/token/", TokenObtainPairView.as_view()),
path("api/token/refresh/", TokenRefreshView.as_view()),
path("api/me/", Me.as_view()),
]
c = APIClient()
print(c.post("/api/token/", {"username": "asha", "password": "wrong"}, format="json").status_code)
tokens = c.post("/api/token/", {"username": "asha", "password": "s3cret-pass"}, format="json").json()
print(sorted(tokens))
print(c.get("/api/me/").status_code)
c.credentials(HTTP_AUTHORIZATION="Bearer " + tokens["access"])
print(c.get("/api/me/").json())
claims = AccessToken(tokens["access"])
print(sorted(k for k in claims.payload if k in ("token_type", "exp", "user_id")), claims["token_type"])
c.credentials(HTTP_AUTHORIZATION="Bearer " + tokens["access"][:-3] + "abc") # tampered signature
print("tampered:", c.get("/api/me/").status_code)
expired = AccessToken.for_user(user)
expired.set_exp(lifetime=-timedelta(seconds=1))
c.credentials(HTTP_AUTHORIZATION="Bearer " + str(expired))
print("expired:", c.get("/api/me/").status_code)
c.credentials()
refreshed = c.post("/api/token/refresh/", {"refresh": tokens["refresh"]}, format="json").json()
print("refresh returns:", sorted(refreshed))
user.is_active = False
user.save()
c.credentials(HTTP_AUTHORIZATION="Bearer " + refreshed["access"])
print("deactivated user:", c.get("/api/me/").status_code)
Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. Requires `pip install djangorestframework djangorestframework-simplejwt`. Token strings are random and time-based, so the snippet prints only claim names and status codes. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3, djangorestframework-simplejwt 5.5.1): 401 ['access', 'refresh'] 401 {'user': 'asha'} ['exp', 'token_type', 'user_id'] access tampered: 401 expired: 401 refresh returns: ['access', 'refresh'] deactivated user: 401
Key points
- Short-lived access token plus longer-lived refresh token
- JWTAuthentication verifies signature and expiry, then loads the user
- Rotation issues a new refresh token; blacklist revokes
- Claims are readable; store tokens carefully; use HTTPS
- Sessions revoke instantly; JWTs suit mobile and service-to-service
Common mistakes
- Storing access tokens in localStorage on pages that can suffer XSS
- Using long access-token lifetimes because refresh feels annoying
- Putting sensitive data in claims
- Assuming logout revokes an access token
- Sharing the SECRET_KEY across services instead of using asymmetric keys
Follow-ups
- How does refresh-token reuse detection work?
- How would you implement logout with SimpleJWT?
- When would you pick sessions instead of JWTs?
Tips
- Describe both tokens and lifetimes
- Name trade-offs of statelessness
- Mention storage in browsers