Talkemi
An OTP must authorize this account and this action: hardening login in a Django REST API
DRF throttles keyed on a user Talkemi never set, and step-up tokens proved an OTP but not whose. Per-account limits and bound, single-use tokens fixed both.
In short
Rate limits on credential endpoints must key on the account and on the source IP, both enforced, with counters shared in Redis; Django REST Framework's user throttles silently fell back to one bucket per IP because authentication didn't set request.user. A step-up token after a one-time code must name the action (scope), the account (subject) and be single use (a Redis delete), and every password change should revoke other sessions and log it.
Talkemi is a language-learning platform I built: students book live classes with real teachers, practise between them with Emi, an AI mentor, and a management team runs the school from a dashboard. Like any product with accounts, it has a handful of endpoints an attacker cares about more than the rest: login, sending and checking one-time codes, password reset, and the re-authentication step in front of sensitive changes. Earlier pieces in this series, starting with Two short transactions around an LLM call, covered the AI side; this one is about the doors.
The rate limits on those endpoints looked configured, and they were. They just weren't counting what they appeared to count. Django REST Framework's standard throttles key on request.user, and Talkemi never sets it for students and teachers, so every limit had quietly collapsed into a single bucket per IP address.
A hotel key card is a useful picture for the rest. Proving you're a guest isn't enough: the card has to open your room and not the one next door, it should be good for this stay only, and when you report it lost, every copy should stop working. Login security in an API comes down to the same three properties.
How the gaps lined up
Authentication in Talkemi runs through custom JWT middleware, which puts the student on request.user_obj and the teacher on request.teacher_user. DRF's user throttles look at request.user, find nobody, and fall back to the client's IP. Two things follow. Everyone behind the same network address shares one budget, and someone trying codes against one account from a pool of rotating IPs never meets a per-account limit at all.
The re-authentication step had a quieter gap. Before a sensitive change, such as a new password, the user proves themselves again with a fresh one-time code and receives a short-lived step-up token. That token proved an OTP had been passed, but not by whom. Without binding it to the profile, any account could earn a token and spend it on another account's session, and an unused token stayed valid for 30 minutes.
Two limits, one token per action
Every credential flow is now limited twice, by account and by source IP, and a request has to pass both. The account key comes from the identifier in the request body and is hashed, so no phone number or email ends up in a cache key. The IP key uses the same client address the rest of the app logs. The counters live in Redis, so the gunicorn workers share one count instead of each enforcing its own copy.
Step-up tokens now carry everything a check needs, and the check refuses on any mismatch:
payload = jwt.decode(token, PUBLIC_KEY, algorithms=["RS256"],
options={"require": ["exp", "jti", "sub"]})
if payload["type"] != TOKEN_TYPE or payload["scope"] != scope:
return False # minted for another action
if not secrets.compare_digest(payload["sub"], subject(profile)):
return False # minted for another account
return bool(redis.delete(f"step-up-jti:{payload['jti']}")) # one use
The scope names the action. An admin resetting someone else's password needs a token with the scope admin_set_password, so a token earned to change your own password can't be pointed at another account. The single-use check is the Redis delete: only the first caller sees the key removed. The unused window dropped from 30 minutes to 5. One product decision sits in the order of calls: the admin endpoint burns the token only after validating the request and resolving the target account, so a typo in the form doesn't cost the admin a new code.
Two smaller changes close the rest. OTP verification attempts are capped per identifier, and every password change goes through one function that sets the password, revokes the profile's other sessions and writes a line to the security log. A self-service change keeps the current session; a recovery reset or an admin reset signs out every device.
How I checked it
The step-up tests drive the real path, from sending the code through verifying it to the sensitive action, rather than minting a token by hand, which is how a broken issuance step can hide behind a passing test. They check that an issued token is spent after one use, that a wrong code never yields a token, and that an admin's token can't change the admin's own password. The throttle tests check that an account's budget survives IP rotation, that two accounts have separate budgets, and that the stored key isn't the raw identifier. The session tests check that another device is rejected after a password change, including when its session was still warm in the cache, and that a recovery reset rejects every device.
Two boundaries are worth stating. The step-up check needs Redis to burn the token, so when Redis is unavailable that check can't pass: it fails closed, and the user retries rather than slipping through. And a burned token is gone even if the action after it fails for another reason, which is why the endpoint validates everything it can first.
What carries over
- Check what your rate limiter actually keys on, especially when authentication doesn't go through the framework's default user.
- Limit credential endpoints per account and per IP; either one alone has an obvious way around it.
- A proof of identity should name the identity, the action and how many times it can be used.
- Put password changes behind one function, so revoking sessions and logging can't be forgotten by the next endpoint.
- Test security flows end to end, from issuance, not from a token you made yourself.
For a student or a teacher, none of this is visible until someone tries their account, and then it's the difference between a lockout that holds and one that doesn't. The design is a set of small bindings, account, action, single use, each enforced in one place, and that's what makes it something a reviewer can check rather than trust.
Further reading
- OWASP Authentication Cheat Sheetcheatsheetseries.owasp.org
- OWASP Multifactor Authentication Cheat Sheetcheatsheetseries.owasp.org
- Django REST Framework throttlingdjango-rest-framework.org
- RFC 7519, JSON Web Token, including the jti claimrfc-editor.org
More writing
-
Don't let the model convert the calendar: Jalali dates in an MCP server for a gold inventory
Why a gold inventory's MCP server converts Jalali dates itself, rejects days that don't exist, and returns every date in both calendars to AI agents.

-
A cold start that draws last launch: persisting the TanStack Query cache in a mobile word game
How ClueShot restores last launch's TanStack Query cache as stale, checks whose it is, and revalidates with ETags so a cold start never opens empty.

-
Two failure handlers, one refund: idempotent cleanup in an async AI image pipeline
How a BullMQ image worker, its failed event and a Telegram bot all reach one refund in MrPicasso, and how two Redis claims keep it to one credit.
