You logged out, the token didn't: sessions vs JWT, refresh tokens and revocation
A JWT with a valid signature gets accepted even after "log out of all devices". How sessions and JWTs work inside, refresh token rotation, denylists, token versions and where to store tokens, with Django code.
A user loses their phone. They log in from a laptop, hit "Log out of all devices" and relax. But the backend runs on JWT, and the access token lives for 24 hours. Whoever has the phone now keeps calling the API until tomorrow evening: the signature is valid, exp hasn't passed, and the server has no reason to say no.
That isn't a JWT bug, it's the design. The token vouches for itself, so the server doesn't hit the database on every request. That's what makes JWT fast, and that's exactly what makes logout hard. Let's look at what actually happens inside sessions and JWTs, build refresh token rotation in Django, compare three ways to revoke a token, and be honest about when a plain session is the better choice.
Two models: state on the server or in the token
With a server-side session, after login the server generates a random identifier (the session key) and hands it to the browser in a cookie. Everything else (who you are, when you logged in) stays on the server: in the database, in Redis, wherever. On every request the server looks up the record by the key from the cookie. The key itself means nothing; it's just a pointer.
In Django that's django.contrib.sessions. The default backend stores data in the django_session table; cached_db reads from the cache first and only goes to the database on a miss:
# settings.py
SESSION_ENGINE = "django.contrib.sessions.backends.cached_db"
SESSION_COOKIE_AGE = 60 * 60 * 24 * 14 # 2 weeks (Django default)
SESSION_COOKIE_SECURE = True # HTTPS only
SESSION_COOKIE_HTTPONLY = True # default: JS cannot read it
SESSION_COOKIE_SAMESITE = "Lax" # default
CSRF_COOKIE_SECURE = True
Login and logout in this model are about as simple as it gets:
# accounts/views.py
from django.contrib.auth import authenticate, login, logout
from django.http import JsonResponse
from django.views.decorators.http import require_POST
@require_POST
def login_view(request):
user = authenticate(
request,
username=request.POST.get("username"),
password=request.POST.get("password"),
)
if user is None:
return JsonResponse({"detail": "invalid credentials"}, status=401)
login(request, user) # rotates the session key (session fixation protection)
return JsonResponse({"ok": True})
@require_POST
def logout_view(request):
logout(request) # flushes the session row: the old cookie is now worthless
return JsonResponse({"ok": True})
logout() deletes the session record. From that moment the old cookie opens nothing, because the server no longer recognises it. Revocation is just deleting a row. On top of that, Django stores a value derived from the password hash in the session and checks it on every request: change the password and sessions on other devices become invalid automatically (update_session_auth_hash() keeps the current one alive).
With a stateless token (JWT), the state lives inside the token. The server writes the user ID, the lifetime and other claims, signs it and hands it to the client. From then on it checks only the signature and the expiry; no database. Several services can verify the token independently with a shared secret or a public key.
What's inside a JWT and what the signature guarantees
A JWT (RFC 7519) is three dot-separated parts: header.payload.signature. The first two are plain base64url-encoded JSON. They are not encrypted; anyone can read them:
import base64
import json
def peek(token: str) -> tuple[dict, dict]:
"""Read a JWT WITHOUT verifying it. For debugging only."""
header_b64, payload_b64, _signature = token.split(".")
def b64(part: str) -> bytes:
return base64.urlsafe_b64decode(part + "=" * (-len(part) % 4))
return json.loads(b64(header_b64)), json.loads(b64(payload_b64))
# peek(token)
# ({'alg': 'HS256', 'typ': 'JWT'},
# {'sub': '42', 'iat': 1763200000, 'exp': 1763200300, 'jti': '...', 'ver': 3})
The signature is computed over the header.payload string. With HS256 (HMAC-SHA256) one secret key both signs and verifies. With asymmetric RS256 or ES256, the auth service signs with a private key and everyone else verifies with the public key. The signature guarantees exactly one thing: the key holder issued the token and nobody touched it afterwards. It does not guarantee the token is still wanted: a blocked user, a password change or a logout has no effect on it.
Two practical rules follow. Don't put anything secret in the payload (phone number, card data, an internal permission list), and use the standard claims: sub (who), exp (until when), iat (issued at), iss/aud (issued by whom, for whom), jti (unique token ID).
Why the naive approach breaks
In many projects JWT first shows up looking like this:
import jwt
# WRONG: the signature is never checked, anyone can forge "sub": "1"
claims = jwt.decode(token, options={"verify_signature": False})
# WRONG: the token chooses its own algorithm
alg = jwt.get_unverified_header(token)["alg"]
claims = jwt.decode(token, key, algorithms=[alg])
# WRONG: long-lived access token, nothing can take it back
jwt.encode({"sub": "42", "exp": now + timedelta(days=30)}, key, algorithm="HS256")
The first line doesn't check the signature at all: edit the payload, put someone else's ID in sub, done. In the second, the token picks its own algorithm. That's the road to the classic attacks: alg: none, or tricking the server into using an asymmetric public key as an HMAC secret. Libraries guard against some of this, but don't rely on it: the list of allowed algorithms must be hard-coded. The third is the most common one: a 30-day access token. Once stolen, nothing stops it for 30 days.
The correct version pins the algorithm, aud, iss and the required claims:
# auth/tokens.py
import uuid
from datetime import timedelta
import jwt
from django.conf import settings
from django.utils import timezone
ALGORITHM = "HS256"
ACCESS_TTL = timedelta(minutes=5)
ISSUER = "api.example.com"
AUDIENCE = "web"
def issue_access_token(user) -> str:
now = timezone.now()
payload = {
"sub": str(user.pk),
"iss": ISSUER,
"aud": AUDIENCE,
"iat": now, # PyJWT converts datetime to a Unix timestamp
"exp": now + ACCESS_TTL,
"jti": uuid.uuid4().hex, # unique id, needed for the denylist
"ver": user.token_version, # needed for "log out everywhere"
}
return jwt.encode(payload, settings.JWT_SIGNING_KEY, algorithm=ALGORITHM)
def decode_access_token(token: str) -> dict:
return jwt.decode(
token,
settings.JWT_SIGNING_KEY,
algorithms=[ALGORITHM], # fixed list, never taken from the token
audience=AUDIENCE,
issuer=ISSUER,
leeway=10, # seconds of clock skew tolerance
options={"require": ["exp", "iat", "sub", "jti"]},
)
Access and refresh: short life, long session
The core fix is splitting the token in two:
- Access token: a short-lived JWT (5–15 minutes). Sent with every API request and verified without the database.
- Refresh token: long-lived (days, weeks), but sent to exactly one endpoint, the one that issues a new access token. It doesn't need to be a JWT. A random string stored as a hash in the database is better, since it gets checked every time anyway.
Now logout means revoking the refresh token, not the access token. The access token survives a few minutes at most.
The next step is rotation: every refresh marks the old token as used and issues a new one. If a used token shows up again, someone else has a copy. In that case we revoke the whole family, every refresh token descended from the same login:
# auth/models.py
from django.conf import settings
from django.contrib.auth.models import AbstractUser
from django.db import models
class User(AbstractUser):
token_version = models.PositiveIntegerField(default=0)
class RefreshToken(models.Model):
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
related_name="refresh_tokens",
)
token_hash = models.CharField(max_length=64, unique=True) # sha256 hex, never the raw token
family = models.UUIDField(db_index=True) # one login = one family
created_at = models.DateTimeField(auto_now_add=True)
expires_at = models.DateTimeField()
used_at = models.DateTimeField(null=True, blank=True)
revoked_at = models.DateTimeField(null=True, blank=True)
# auth/refresh.py
import hashlib
import secrets
import uuid
from datetime import timedelta
from django.db import transaction
from django.utils import timezone
from .models import RefreshToken
from .tokens import issue_access_token
REFRESH_TTL = timedelta(days=30)
class RefreshError(Exception):
pass
def _hash(raw: str) -> str:
return hashlib.sha256(raw.encode()).hexdigest()
def issue_refresh_token(user, family=None) -> str:
raw = secrets.token_urlsafe(32)
RefreshToken.objects.create(
user=user,
token_hash=_hash(raw),
family=family or uuid.uuid4(),
expires_at=timezone.now() + REFRESH_TTL,
)
return raw
def rotate_refresh_token(raw: str) -> tuple[str, str]:
now = timezone.now()
reuse_detected = False
with transaction.atomic():
token = (
RefreshToken.objects.select_for_update(of=("self",))
.select_related("user")
.filter(token_hash=_hash(raw))
.first()
)
if token is None or token.revoked_at or token.expires_at <= now:
raise RefreshError("invalid refresh token")
if not token.user.is_active:
raise RefreshError("user is inactive")
if token.used_at is not None:
# An already rotated token came back: someone has a copy.
# Revoke the whole family, the real user will log in again.
RefreshToken.objects.filter(
family=token.family, revoked_at__isnull=True
).update(revoked_at=now)
reuse_detected = True
else:
token.used_at = now
token.save(update_fields=["used_at"])
new_raw = issue_refresh_token(token.user, family=token.family)
access = issue_access_token(token.user)
# Raise AFTER the block: raising inside atomic() would roll back the revoke.
if reuse_detected:
raise RefreshError("refresh token reuse detected")
return access, new_raw
Two subtle points here. First, select_for_update(): we lock the row so two parallel requests can't both see the same token as unused and mint two new ones. Second, the exception is raised after the atomic() block. Raise it inside and Django rolls back the transaction, taking the UPDATE that revoked the family with it.
Revoking a token: three approaches
The access token still lives for a while. Sometimes even that is too long: the user was blocked, or they pressed "log out everywhere". There are three main options:
| Approach | How it works | Cost |
|---|---|---|
| Short TTL | Access lives 5 minutes, refresh is revoked | Revocation lags by up to 5 minutes |
Denylist (jti) |
Revoked jti kept in Redis until exp |
A Redis lookup on every request |
Version (ver) |
User has token_version, compared with the token's value |
Loading the user on every request |
A denylist fits single-device logout: the key's TTL equals the token's remaining lifetime, so Redis cleans up after itself. The version counter is for "log out everywhere": bumping it by one instantly invalidates every token issued with the old value.
# auth/revoke.py
import time
from django.core.cache import cache
from django.db.models import F
from django.utils import timezone
from .models import RefreshToken, User
def revoke_access_token(claims: dict) -> None:
"""Logout on this device: deny the jti until the token would expire anyway."""
ttl = claims["exp"] - int(time.time())
if ttl > 0:
cache.set(f"jwt:deny:{claims['jti']}", 1, timeout=ttl)
def logout_everywhere(user) -> None:
"""Every access token with the old "ver" and every refresh token dies."""
User.objects.filter(pk=user.pk).update(token_version=F("token_version") + 1)
RefreshToken.objects.filter(user=user, revoked_at__isnull=True).update(
revoked_at=timezone.now()
)
A DRF authentication class ties it all together:
# auth/authentication.py
import jwt
from django.contrib.auth import get_user_model
from django.core.cache import cache
from rest_framework import authentication, exceptions
from .tokens import decode_access_token
class JWTAuthentication(authentication.BaseAuthentication):
def authenticate(self, request):
parts = authentication.get_authorization_header(request).split()
if not parts or parts[0].lower() != b"bearer":
return None # let other authentication classes try
if len(parts) != 2:
raise exceptions.AuthenticationFailed("Malformed Authorization header")
try:
claims = decode_access_token(parts[1].decode())
except jwt.InvalidTokenError: # includes ExpiredSignatureError
raise exceptions.AuthenticationFailed("Invalid or expired token")
if cache.get(f"jwt:deny:{claims['jti']}"):
raise exceptions.AuthenticationFailed("Token revoked")
User = get_user_model()
user = User.objects.filter(pk=claims["sub"], is_active=True).first()
if user is None or user.token_version != claims["ver"]:
raise exceptions.AuthenticationFailed("Token revoked")
return user, claims
def authenticate_header(self, request):
return "Bearer" # makes DRF answer 401 instead of 403
Notice that the moment you add a denylist or a version check, your JWT is no longer stateless. Every request consults server-side state anyway. That's fine, but if you hit Redis or the database every time, you've given up JWT's main advantage, and a plain session is probably simpler.
Where to store the token: localStorage or a cookie
Two attacks pull in opposite directions here.
XSS (foreign JavaScript running on your page). Any script on the page can read localStorage. One malicious npm package or one piece of unescaped HTML is enough: the token is shipped to another server and the attacker uses it from their own machine. An HttpOnly cookie can't be read from JavaScript. XSS can still send requests as the user while the page is open, but it can't walk away with the token.
CSRF (a request triggered from another site). The browser attaches cookies automatically, so a form on a hostile site "brings" yours along. The defences are the SameSite attribute (Lax withholds the cookie from cross-site POSTs and subrequests, allowing only top-level GET navigations; Strict withholds it from all cross-site requests) and Django's CSRF token. A token in the Authorization header isn't exposed to CSRF, because the browser never adds it on its own.
A combination that works well in practice:
- access token in SPA memory (a JavaScript variable), sent as
Authorization: Bearer; - refresh token in an
HttpOnly; Secure; SameSite=Strictcookie withPathlimited to the auth endpoints; - after a page reload, the SPA first calls
/api/auth/refresh/to get a fresh access token.
# auth/views.py
from django.http import JsonResponse
from django.views.decorators.http import require_POST
from .refresh import REFRESH_TTL, RefreshError, rotate_refresh_token
from .tokens import ACCESS_TTL
REFRESH_COOKIE = "refresh"
REFRESH_PATH = "/api/auth/"
@require_POST # a plain Django view: CsrfViewMiddleware still protects it
def refresh_view(request):
raw = request.COOKIES.get(REFRESH_COOKIE)
if not raw:
return JsonResponse({"detail": "no refresh token"}, status=401)
try:
access, new_raw = rotate_refresh_token(raw)
except RefreshError:
response = JsonResponse({"detail": "invalid refresh token"}, status=401)
response.delete_cookie(REFRESH_COOKIE, path=REFRESH_PATH, samesite="Strict")
return response
response = JsonResponse(
{"access": access, "expires_in": int(ACCESS_TTL.total_seconds())}
)
response.set_cookie(
REFRESH_COOKIE,
new_raw,
max_age=int(REFRESH_TTL.total_seconds()),
path=REFRESH_PATH, # the browser sends it only to /api/auth/...
secure=True,
httponly=True,
samesite="Strict",
)
return response
refresh_view is a plain Django view, so CsrfViewMiddleware protects it: the SPA has to send the X-CSRFToken header. DRF's APIView only enforces CSRF for SessionAuthentication, so if you move a cookie-based endpoint into DRF, you have to add CSRF checks yourself.
Pitfalls in production
- Parallel refresh. Two tabs notice the expired access token at the same moment and both refresh. The second one sends an already used token, reuse detection revokes the family, and the user gets logged out "for no reason". Fix it with a single in-flight refresh on the client that all requests wait on, or a grace period of a few seconds on the server for a just-used token.
- Clock skew.
expandiatdepend on server clocks. Without NTP, services start rejecting each other's tokens as "issued in the future"; keepleewayto a few seconds. - Key rotation. Change the HS256 secret and every token dies at once. With asymmetric keys, a
kidin the header plus accepting several public keys at a time makes rotation smooth. - Fat payloads. Roles and permission lists in the token make every request heavier, and when permissions change, the old token keeps the old rights.
- Raw refresh tokens at rest. If the database stores raw refresh tokens, a database dump is a key to every account. Store only the hash.
- Frontend-only logout.
localStorage.removeItem()is not a logout. If nothing is revoked on the server, a stolen copy keeps working. - Table bloat.
RefreshTokenanddjango_sessionkeep growing. Schedule a periodic job that deletes expired rows; for sessions Django ships theclearsessionscommand.
When a session is the better choice
For many Django projects the honest answer is: sessions. If frontend and backend live under one domain (or one site), with server-rendered pages or an SPA on the same site, sessions give you for free: instant logout, an HttpOnly cookie, ready-made CSRF protection, and compatibility with the admin. One Redis read per request is usually negligible; don't guess, measure it under your own load.
JWT earns its keep when several independent services must verify a token without calling a central one, for short-lived service-to-service tokens, or when an external identity provider (OpenID Connect) already issues JWTs. A mobile app doesn't require JWT either: a plain random (opaque) token stored in the database is often enough, and it's trivial to revoke.
Checklist
- Allowed algorithms are hard-coded;
verify_signatureis never turned off. exp,iat,sub,jtiare required;audandissare checked.- Access token 5–15 minutes; refresh token stored hashed, with rotation and reuse detection.
- Single-device logout via a
jtidenylist (TTL = remaining lifetime); "log out everywhere" viatoken_version. - No tokens in
localStorage; refresh in anHttpOnly; Secure; SameSitecookie with a narrowPath. - Every state-changing endpoint that relies on cookies is CSRF-protected.
- Nothing secret in the payload.
- Parallel refresh handled on the client or with a grace period.
- Expired tokens and sessions are purged periodically.
Takeaway
With sessions the state lives on the server, so revocation is easy. With JWT the state lives in the token, so verification is cheap and revocation is hard. A short access token, a rotating refresh token and a jti/version check solve that, at the price of some statelessness. If you have one site and one backend, look at Django sessions first: they already do the right thing.
// comments
Loading comments...