Backend
Stateless OTP Login in FastAPI with JWT and Redis
Password databases are a liability. Build a stateless OTP login flow in FastAPI using signed JWTs as verification tokens and Redis for single-use enforcement.
- Published
- Reading
- 8 min
- Author
- Fidelis Uwem Joseph
Series · Part 4 of 9FastAPI in Production
- FastAPI Layered Architecture — Routes, Services, and Repositories
- Alembic with SQLAlchemy 2.0 Async — Migrations That Hold in Production
- Alembic Async Migrations and Idempotent Database Seeding in FastAPI
- Stateless OTP Login in FastAPI with JWT and Redis
- Async Email Delivery in FastAPI — Two SMTP Paths, One Jinja2 Template System
- Celery + Redis in Production — Task Reliability with acks_late and Retry Backoff
- Monitoring Celery with Flower — Local Setup and SSH Tunnel for Remote Servers
- Mailpit as a Dev SMTP Catch-All Behind Traefik
- MinIO as a Self-Hosted S3 Backend in Docker
Railway removed passwords entirely. You enter your email, get a six-digit code, and you are in. No password field, no “forgot password” flow, no credential database to rotate when the breach happens. This post implements the same pattern in FastAPI: a stateless OTP login that stores nothing in the database, embeds the code in a signed JWT, and enforces single-use via Redis. The full flow is under 120 lines of application code.
Prerequisites
- Python 3.11+
- FastAPI 0.115+
python-jose,redis,aiosmtplib,pydantic-settingsinstalled- Working knowledge of JWT claims and Redis key expiry
Background
The naive OTP approach writes a code and an expiry timestamp to the database on every login request, then does a read-then-delete on verification. It works, but it adds two database operations to the critical path and leaks codes if the database is compromised.
The stateless alternative embeds the code inside a signed JWT. The server signs the token, returns it to the client, and verifies the signature on submit. No row written. No query on verify. The token is its own proof of issuance.
Implementation
1. Token creation and code generation
Derive a separate OTP secret from the application secret by appending a fixed suffix. Tokens carry a type: otp claim so they are rejected by the access token verifier even if submitted to a protected route.
OTP_EXPIRE_MINUTES = 10OTP_ALGORITHM = "HS256"OTP_SECRET = f"{settings.SECRET_KEY}-otp"
def generate_otp_code() -> str: return "".join(random.choices(string.digits, k=6))
def create_otp_token(email: str, code: str, extra_claims: dict | None = None) -> str: payload = { "sub": email, "code": code, "exp": datetime.now(timezone.utc) + timedelta(minutes=OTP_EXPIRE_MINUTES), "type": "otp", **(extra_claims or {}), } return jwt.encode(payload, OTP_SECRET, algorithm=OTP_ALGORITHM)The derived secret and the type claim are independent guards. Decoding an OTP token with the main secret fails at signature verification. Submitting an OTP token to a protected route fails at the type check. Both must hold.
2. Request endpoint
The request endpoint generates a code, signs it into a token, sends the email, and returns the token to the client. It always returns success regardless of whether the email is registered. The email send fires only for known addresses, but the response is identical either way.
@router.post("/otp/request")async def request_otp(payload: OTPRequest): return await auth_service.request_otp(payload.email)async def request_otp(self, email: str) -> dict: code = generate_otp_code() token = create_otp_token(email, code) await send_otp_email(email, code) return {"message": "Code sent. Check your email.", "verification_token": token}The client stores the verification_token from the response and submits it alongside the code on the next request. The server stores neither.
3. Verify endpoint
async def verify_otp( self, email: str, code: str, verification_token: str, redis) -> dict: blacklist_key = f"otp_used:{verification_token}" if await redis.get(blacklist_key): raise UnAuthorizedException(detail="Code has already been used.")
try: payload_data = decode_otp_token(verification_token) except Exception: raise UnAuthorizedException(detail="Invalid or expired verification token.")
embedded_code: str = payload_data["code"] if not hmac.compare_digest(embedded_code, code): raise UnAuthorizedException(detail="Incorrect code.")
exp = payload_data.get("exp", 0) ttl = max(1, exp - int(time_module.time())) await redis.set(blacklist_key, "1", ttl=ttl)
return { "message": "Verified successfully.", "access_token": create_access_token(subject=email), "refresh_token": create_refresh_token(subject=email), "token_type": "bearer", }Three things happen in a specific order.
The Redis blacklist check runs before any token decoding. This prevents a timing oracle: an attacker submitting a used token repeatedly and measuring decode timing differences learns nothing if the check is a flat cache lookup first.
hmac.compare_digest does constant-time string comparison. A plain == leaks the length of the match through timing. compare_digest does not.
The blacklist TTL is derived from the token’s remaining lifetime, not a fixed value. A hardcoded TTL shorter than the token’s actual expiry leaves a window where the token is still valid but the blacklist entry has expired. Always use exp - time.time().
4. Token decode with type guard
def decode_otp_token(token: str) -> dict: try: payload = jwt.decode(token, OTP_SECRET, algorithms=[OTP_ALGORITHM]) if payload.get("type") != "otp": raise JWTError("Invalid token type.") return payload except JWTError as e: raise JWTError(str(e))The type guard rejects access tokens submitted to the OTP verify endpoint. Without it, an attacker with a valid access token could craft a payload containing a known code claim and pass verification.
Testing and Verification
Run the full flow against a local Mailpit instance:
# Step 1: request a codecurl -s -X POST http://localhost:8000/api/v1/auth/otp/request \ -H "Content-Type: application/json" \ -d '{"email": "alice@example.com"}' | jq .Expected response:
{ "message": "Code sent. Check your email.", "verification_token": "eyJhbGciOiJIUzI1NiIsInR5..."}# Step 2: open Mailpit at http://localhost:8025, copy the code, then verifycurl -s -X POST http://localhost:8000/api/v1/auth/otp/verify \ -H "Content-Type: application/json" \ -d '{ "email": "alice@example.com", "code": "482916", "verification_token": "eyJhbGciOiJIUzI1NiIsInR5..." }' | jq .Expected response:
{ "message": "Verified successfully.", "access_token": "eyJ...", "refresh_token": "eyJ...", "token_type": "bearer"}# Step 3: replay the same token and code# Expected: 401 "Code has already been used."To verify secret isolation, decode a valid access token and submit it to /otp/verify. It will fail at decode_otp_token because the OTP secret does not match the access token secret.
Pitfalls
Production Considerations
The OTP email is sent in the request path because the user is waiting for it. A Celery task adds latency that the user cannot observe and gains nothing. If SMTP latency becomes a bottleneck at high volume, move the send to Celery and return the verification_token immediately, then surface delivery status via a polling endpoint.
The six-digit numeric space is 10^6 combinations. With a 10-minute expiry and the token bound to a specific email, brute force is not practical. Rate-limiting /otp/verify per IP closes it entirely regardless.
Hardening the flow
The walkthrough shows the shape of a stateless OTP flow. Five problems need fixing before it protects anything.
1. Never put the code in the token
A JWT is three base64url segments, and the middle one is the payload in plain JSON. The signature stops anyone from changing the payload. It does nothing to stop them reading it. Anyone who calls /otp/request gets back a token containing the code:
$ echo "$TOKEN" | cut -d. -f2 | base64 -d 2>/dev/null{"sub":"alice@example.com","code":"482916","exp":1749650000,"type":"otp"}That defeats the point of emailing the code. Store a keyed hash of the code instead. The server can recompute it on verify, and the client cannot reverse it, because it does not have the key:
import hashlibimport hmacimport secretsimport uuid
OTP_SECRET = hmac.new(settings.SECRET_KEY.encode(), b"otp-token-v1", hashlib.sha256).hexdigest()CODE_KEY = hmac.new(settings.SECRET_KEY.encode(), b"otp-code-v1", hashlib.sha256).digest()
def code_digest(email: str, code: str) -> str: # bound to the email, so a code for one address is useless for another msg = f"{email.strip().lower()}:{code}".encode() return hmac.new(CODE_KEY, msg, hashlib.sha256).hexdigest()
def generate_otp_code() -> str: return f"{secrets.randbelow(1_000_000):06d}"
def create_otp_token(email: str, code: str) -> str: payload = { "sub": email.strip().lower(), "cd": code_digest(email, code), "jti": uuid.uuid4().hex, "exp": datetime.now(timezone.utc) + timedelta(minutes=OTP_EXPIRE_MINUTES), "type": "otp", } return jwt.encode(payload, OTP_SECRET, algorithm=OTP_ALGORITHM)Two smaller fixes ride along. secrets.randbelow replaces random.choices: the random module is a predictable generator meant for simulations, not security. And both keys are now derived with HMAC under a label rather than by appending -otp to the main secret, so each key is independent of the other and of the access-token key.
A six-digit code has only a million possible values, so an attacker who obtains the token could, in principle, compute the digest for each one offline. The keyed HMAC is what prevents that: without CODE_KEY, there is nothing to compare against.
2. Check that the email matches the token
verify_otp receives both email and verification_token, but never checks that they belong together. Compare the request’s email with the token’s sub. With the digest bound to the email, a mismatch also fails the code check, but an explicit check gives a clearer error and does not depend on that detail.
3. Limit attempts per token
The production section argues that a million combinations within ten minutes is impractical to brute force. Without a limit, it is not: a script can submit hundreds of guesses a second against one token. Per-IP rate limiting helps, but attackers rotate IPs. Limit attempts per token instead, using the jti:
MAX_ATTEMPTS = 5
async def register_attempt(redis, jti: str, ttl: int) -> None: key = f"otp_attempts:{jti}" attempts = await redis.incr(key) if attempts == 1: await redis.expire(key, ttl) if attempts > MAX_ATTEMPTS: raise UnAuthorizedException(detail="Too many attempts. Request a new code.")Five guesses at one-in-a-million odds gives an attacker a 0.0005% chance per token. Rate-limit /otp/request per email as well, so they cannot simply request fresh tokens in a loop, and so nobody can flood a victim’s inbox.
4. Make “use once” atomic
redis.get followed by redis.set has a gap between the two calls. Two requests with the same valid code that arrive together can both pass the get before either has run the set, and both receive tokens. A single SET ... NX closes the gap: it writes the key only if it does not already exist, and reports whether it did.
5. The verify function, hardened
Putting it together, using redis.asyncio from redis-py:
async def verify_otp(self, email: str, code: str, verification_token: str, redis) -> dict: try: claims = decode_otp_token(verification_token) except JWTError: raise UnAuthorizedException(detail="Invalid or expired verification token.")
email = email.strip().lower() jti, exp = claims["jti"], claims["exp"] if not hmac.compare_digest(claims["sub"], email): raise UnAuthorizedException(detail="Invalid or expired verification token.")
ttl = max(1, exp - int(time.time())) await register_attempt(redis, jti, ttl)
if not hmac.compare_digest(claims["cd"], code_digest(email, code)): raise UnAuthorizedException(detail="Incorrect code.")
# atomic single use: only the first request to reach this line wins first_use = await redis.set(f"otp_used:{jti}", "1", nx=True, ex=ttl) if not first_use: raise UnAuthorizedException(detail="Code has already been used.")
return issue_session(email)Keying Redis by jti instead of the whole token keeps keys short and means the same token cannot be replayed under a different encoding. The single-use mark is written only after the code is correct, so failed guesses cannot burn a legitimate user’s token, while the attempt counter still caps how many guesses are possible.
6. Make sure the email is the only channel
One last check on the response from /otp/request. It should contain the token and a message, nothing else. Decode a fresh token as in the first example and confirm you see cd, not code. Add that as a test so it cannot regress:
def test_token_does_not_reveal_code(client): res = client.post("/api/v1/auth/otp/request", json={"email": "alice@example.com"}) token = res.json()["verification_token"] claims = jwt.get_unverified_claims(token) assert "code" not in claims assert len(claims["cd"]) == 64 # hex SHA-256 digestAdd tests for the other guarantees too: a sixth guess on the same token is rejected with “too many attempts”, a token issued for one email fails for another, and two concurrent verifies with the right code produce exactly one session.
When to keep state after all
The stateless design trades a database row for a token the client must carry between two requests. That suits API-first clients and mobile apps. If you need to revoke every pending code for an account (for example after a reported compromise), or show users their recent sign-in attempts, a small Redis record per request (otp:{email} -> digest, attempts, with a TTL) is simpler than encoding more into the token. Both designs need the same five fixes above.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| Token payload shows the code | Raw code stored in a claim | Store a keyed HMAC digest |
| Same code works twice under load | get then set race | SET NX after a successful check |
| Unlimited guesses on one token | No per-token attempt limit | Count attempts by jti |
| Code for one email works for another | sub not compared, digest not bound to email | Compare sub, include email in the digest |
| Codes look predictable in tests | random module | secrets.randbelow |
Wrapping Up
The OTP state lives in a signed JWT. Redis enforces single-use. No database table is involved and no secret is stored at rest. The entire flow across otp.py, auth_service.py, and the two route handlers is under 120 lines.
The next problem you will hit is delivery reliability. SMTP against a transactional provider (Postmark, Resend, or SendGrid) adds delivery webhooks and reduces latency compared to a self-hosted relay.
- Full source: github.com/joseph-fidelis