Guide · November 26, 2026 · 4 min read
2FA recovery codes and session management in Django
Add one-time recovery codes to TOTP two-factor auth and an active-sessions screen that really signs devices out — access tokens included — in a Django REST API.
Two features turn a login system into account security: a way back in when the authenticator phone is lost, and a way to kick out a device you no longer trust. Both look simple and both have a trap. This guide shows how to build them in a Django REST Framework API that issues JWTs with SimpleJWT.
Part 1: recovery codes
Without recovery codes, a user with an authenticator app who loses their phone is locked out, and support has to verify their identity by hand — the most common social-engineering target there is.
Generate, show once, store a hash
ALPHABET = "abcdefghjkmnpqrstuvwxyz23456789" # no 0/o, 1/i/l
def _new_code():
while True:
raw = "".join(secrets.choice(ALPHABET) for _ in range(8))
if not raw.isdigit(): # would look like a 6-digit app code
return f"{raw[:4]}-{raw[4:]}"
def _hash(user, code):
return salted_hmac("users.recovery-code", f"{user.pk}:{normalize(code)}", algorithm="sha256").hexdigest()
- Use
secrets, neverrandom. - Store only the keyed hash. The plain codes are returned once, when the authenticator app is confirmed, and never again.
- A fast keyed hash is enough: each code has about 40 bits of entropy and the second sign-in step is rate-limited. A slow password hasher would make every attempt check ten slow hashes.
- Include the user id in the hashed value so one person’s code can never match another’s.
Spend atomically
spent = RecoveryCode.objects.filter(
user=user, code_hash=_hash(user, code), used_at__isnull=True
).update(used_at=timezone.now())
return spent == 1
The UPDATE … WHERE used_at IS NULL is what makes two simultaneous sign-ins with the same code succeed only once. A read-then-write would let both through.
The details that make it usable and safe
- Accept it in the same box. People type the recovery code where the app code goes. Normalize case, spaces and dashes, and tell an 8-character code apart from a 6-digit one.
- Count failures toward the same lockout as wrong app codes.
- Email the owner whenever a recovery code is used, with how many are left.
- Regenerating needs the password and invalidates the previous set.
- Only for authenticator apps. With email codes the mailbox is the way back in; leftover codes from an earlier app setup must not open the account.
- Drop them when someone else takes over the account. If the real owner of an address claims an account someone registered with it (through Google sign-in or an invitation), remove the second factor and recovery codes the impostor set up.
Part 2: sessions you can actually close
An “active sessions” screen is only honest if closing a session ends it. With JWTs that is harder than it sounds.
The problem with blacklists
SimpleJWT’s blacklist stops a refresh token. The access token already handed out keeps working until it expires — five minutes with SimpleJWT’s defaults, an hour in many real configurations (SaaS Dock’s included). Sign out a stolen laptop and it stays signed in for the rest of that window.
A session id in every token
Give each sign-in a session id and put it in the refresh token. SimpleJWT copies custom claims into every access token it derives and keeps them when it rotates the refresh token, so every token from that sign-in carries the same sid:
def start_session(user, request):
sid = uuid.uuid4().hex
UserSession.objects.create(user=user, sid=sid, last_activity_at=timezone.now(), ...)
refresh = RefreshToken()
refresh["user_id"] = str(user.pk)
refresh["sid"] = sid
# record it as outstanding *after* the claim is set
return refresh
Every sign-in path — password, second factor, Google — must go through this one function, or some sessions will be invisible and unclosable.
Refuse closed sessions on every request
class SessionJWTAuthentication(JWTAuthentication):
def get_validated_token(self, raw_token):
token = super().get_validated_token(raw_token)
if sessions.is_closed(token.get("sid")):
raise AuthenticationFailed("This session has been closed.", code="session_closed")
return token
Do the same in the refresh endpoint. is_closed reads the session row, with the cache only sparing the query: trusting the cache alone brings closed sessions back after a cache flush. A sid with no row at all should count as closed.
Tokens from before the change
Tokens issued before you add sessions have no sid, and a rotation copies the payload as it is — left alone, such a chain lives forever, unlisted. Adopt it on its first refresh: use the old token’s jti as its session id, create the row, and re-sign the rotated pair with the claim.
What to show and what to offer
- Browser, operating system, IP and last activity — taken from requests made by the browser. If your Next.js server signs in and refreshes on the user’s behalf, its user agent says nothing about the device.
- “Sign out” per session (not the current one — that is the normal sign-out), and “Sign out all other sessions”.
- Changing the password closes every other session and keeps the current one.
On the frontend, make a 401 from the refresh endpoint sign the browser out, so a session closed elsewhere leaves cleanly instead of showing network errors. See NextAuth + Django JWT refresh.
Checklist
- Recovery codes:
secrets, keyed hash, shown once, atomic spend, lockout, owner notified, password to regenerate - Codes removed on switching to email 2FA, disabling 2FA, deleting or handing over the account
- A
sidclaim on every token; one function for every sign-in path - Access and refresh tokens refused for closed sessions; row is the record, cache an optimization
- Legacy tokens adopted on first refresh
- Password change keeps the current session, closes the rest
SaaS Dock includes both features in its Django API and Next.js settings screens, with tests for double spending, cross-user codes, legacy tokens and remote sign-out. See the auth section.
Frequently asked questions
- How should 2FA recovery codes be stored?
- Never in plain text. Store a keyed hash of each code (for example HMAC-SHA256 with the project's secret key), show the plain codes once when they are generated, and mark a code as used with an atomic UPDATE so it cannot be spent twice.
- Why doesn't blacklisting a refresh token sign a device out immediately?
- Because access tokens are stateless: a token issued before the sign-out stays valid until it expires, often an hour. To end a session at once, put a session id claim in every token and have the API refuse tokens whose session has been closed.
Keep reading
- NextAuth + Django JWT: refresh tokens without session leaksHow to store Django REST Framework JWTs in NextAuth, refresh them safely from server and client, avoid handing one user another user's tokens, and sign out cleanly.
- Idempotent Stripe webhooks in Django: what actually mattersSignature checks, event dedupe, out-of-order delivery, Celery retries and replaying lost events — the Stripe webhook patterns a Django SaaS needs in production.
- Multi-tenant SaaS with Django and Next.js: a practical guideHow to model tenants, resolve the active workspace, scope every query and switch workspaces safely in a Django REST Framework API with a Next.js frontend.