← Back to FastAPI
Lesson 6.3 · Auth & Security

Login with OAuth2 and JWT

Log in once with a username and password, get a signed token, and send it with every request. Take a JWT apart, attack it five ways, build POST /token with OAuth2’s password form, and add a refresh token so access tokens can be short. Plus two real leaks: a bad token that crashed the server with 500, and a 7-day refresh token that worked as an access token.

Intermediate40 min

What you will be able to do

  • Explain what a JWT is, and what its three parts hold
  • Make and check tokens with PyJWT
  • Know which token attacks the signature stops - and which it does not
  • Build POST /token with OAuth2PasswordRequestForm
  • Read the token with OAuth2PasswordBearer
  • Use a short access token and a longer refresh token
  • Turn every bad token into a 401, never a 500

The idea, in plain English

Sending the password with every request would be slow (Argon2 takes about 43 ms, Lesson 6.2) and risky - the password would sit in every request and every log. So the client logs in ONCE: it sends the username and password, and gets back a token. After that it sends only the token, as Authorization: Bearer <token>.

A JWT (JSON Web Token) is a small piece of JSON - like "user 1, valid until 15:30" - plus a signature made with a secret key that only your server knows. Anyone can READ a JWT; nobody can CHANGE one without breaking the signature. So the server can trust it without storing it anywhere.

OAuth2 is the standard that says how the login looks: POST /token with a form holding username and password, and an answer with access_token and token_type "bearer". FastAPI has both halves ready: OAuth2PasswordRequestForm and OAuth2PasswordBearer - and /docs gets a working login button for free. FastAPI 0.143.0, PyJWT 2.15.1, pwdlib 0.3.1.

Worked example: A login API for ravi with POST /token, GET /me and POST /refresh - tested with TestClient and curl, and attacked with changed, expired and wrong-type tokens.

workflowLog in once, then send the tokenstep 1 / 3

1 - Log in

The password is checked with Argon2 (Lesson 6.2). The answer is two signed tokens.

right password
200 access + refresh token
wrong password
401

The password is sent once. After that, only the signed token travels. Real results from our login API.

Words you will see in this lesson

A few words about tokens.

Small dictionary
TokenA string the client gets at login and sends back to prove who it is.
JWTJSON Web Token - a token that carries JSON and a signature. Say "jot".
ClaimOne fact inside a JWT, such as "sub": "1" or "exp": 1794748065.
SignatureA check value made from the token and the secret key. Change one letter and it no longer fits.
Access tokenThe short-lived token sent with every request.
Refresh tokenA longer-lived token used only to get a new access token.
OAuth2A standard for logins and tokens. We use its simplest form, the password flow.

An everyday example: a cinema ticket

  • At the counter you pay and show your ID once - that is the login.
  • You get a ticket: hall 3, seat 12, today at 18:00 - the claims. Anyone can read it.
  • It has a hologram stamp that only the cinema can make - the signature. Change "hall 3" to "hall 1" with a pen and the usher sees it at once.
  • The ticket is valid only today - the expiry.
  • The usher does not phone the counter for every guest. The stamp is enough - that is why tokens are fast.

Example 1 - a JWT, taken apart and attacked

pip install pyjwt, then run jwt_basics.py:

  • jwt.encode makes a token from a dict, the secret key and the algorithm HS256. Ours was 119 characters.
  • A JWT is three parts joined by dots: header, payload, signature. The first two are just base64 - we decoded them without any key. So never put a password or anything secret in a token.
  • "sub" (subject) is who the token is about - the user id, as a string. "exp" is when it stops working, in seconds since 1970.
  • jwt.decode checks the signature AND the expiry. It returned the claims for the real token.
  • Then five attacks, all refused: a changed payload (sub 1 -> 3), a token signed with another key, an expired token, a token with alg "none" and no signature, and a decode call without algorithms=.
Example 1 - jwt_basics.py
import base64 import json from datetime import datetime, timedelta, timezone import jwt SECRET_KEY = "45a1456a3ed0187fc7716d558f0c688c48e1e199e89a95b1264ce1f3317c6394" def b64(part): # JWT parts are base64url without padding return json.loads(base64.urlsafe_b64decode(part + "=" * (-len(part) % 4))) def check(label, token, **kwargs): try: claims = jwt.decode(token, kwargs.pop("key", SECRET_KEY), algorithms=["HS256"], **kwargs) print(f"{label:<26} -> OK {claims}") except jwt.InvalidTokenError as e: print(f"{label:<26} -> FAIL {type(e).__name__}: {e}") # 1. Make a token now = datetime.now(timezone.utc) token = jwt.encode({"sub": "1", "exp": now + timedelta(minutes=15)}, SECRET_KEY, algorithm="HS256") print("token:", token) print("length:", len(token), "characters") # 2. Take it apart - anyone can read it header, payload, signature = token.split(".") print("header: ", b64(header)) print("payload:", b64(payload)) print("signature:", signature) # 3. Check it, then attack it check("the real token", token) fake_payload = base64.urlsafe_b64encode(json.dumps( {"sub": "3", "exp": b64(payload)["exp"]}).encode()).rstrip(b"=").decode() check("sub changed to 3", f"{header}.{fake_payload}.{signature}") check("someone else's key", jwt.encode({"sub": "1", "exp": now + timedelta(minutes=15)}, "another-secret-of-32-bytes-or-more!!", algorithm="HS256")) check("expired 1 minute ago", jwt.encode({"sub": "1", "exp": now - timedelta(minutes=1)}, SECRET_KEY, algorithm="HS256")) none_header = base64.urlsafe_b64encode(b'{"alg":"none","typ":"JWT"}').rstrip(b"=").decode() check('alg "none", no signature', f"{none_header}.{payload}.") # 4. Forgetting algorithms= is not allowed try: jwt.decode(token, SECRET_KEY) except jwt.DecodeError as e: print(f"{'no algorithms= given':<26} -> FAIL", type(e).__name__ + ":", e)
Output
token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxIiwiZXhwIjoxNzk0NzQ4MDM1fQ.B6SsQ12FgFhR_Wy8iuTJNtRuS_Ru_gaLup6GhmrmDdc length: 119 characters header: {'alg': 'HS256', 'typ': 'JWT'} payload: {'sub': '1', 'exp': 1794748035} signature: B6SsQ12FgFhR_Wy8iuTJNtRuS_Ru_gaLup6GhmrmDdc the real token -> OK {'sub': '1', 'exp': 1794748035} sub changed to 3 -> FAIL InvalidSignatureError: Signature verification failed someone else's key -> FAIL InvalidSignatureError: Signature verification failed expired 1 minute ago -> FAIL ExpiredSignatureError: Signature has expired alg "none", no signature -> FAIL InvalidAlgorithmError: The specified alg value is not allowed no algorithms= given -> FAIL DecodeError: It is required that you pass in a value for the "algorithms" argument when calling decode().

What the signature protects - and what it does not

Signed is not secret
Changing the tokenStopped. "sub changed to 3" failed: InvalidSignatureError.
Making your own tokenStopped - without SECRET_KEY. With it, anyone can make an admin token. Guard the key.
Using an old tokenStopped after exp. Until then, a stolen token works - so keep access tokens short.
Reading the tokenNOT stopped. The payload is plain base64. No passwords, emails or secrets inside.
alg "none"Stopped, because algorithms=["HS256"] lists the ONE algorithm we accept.

Watch out: Always pass algorithms=[...] with exactly the algorithm you sign with. PyJWT 2 refuses to decode without it - older libraries accepted "none" and let anyone make tokens.

Example 2 - the login API

login.py puts it together. pip install "fastapi[standard]" sqlmodel "pwdlib[argon2]" pyjwt:

  • create_token puts four claims in: sub (the user id), type ("access" or "refresh"), iat (issued at) and exp.
  • issue_tokens makes both: access for 15 minutes, refresh for 7 days.
  • read_token is the ONE place tokens are checked: signature and expiry by jwt.decode, then the type. Every failure is a 401 with WWW-Authenticate: Bearer.
  • POST /token takes OAuth2PasswordRequestForm - a form, not JSON - and checks the password the way Lesson 6.2 did, dummy hash included.
  • OAuth2PasswordBearer(tokenUrl="token") reads the Bearer header, like HTTPBearer in Lesson 6.1, and tells /docs where to log in.
  • POST /refresh trades a refresh token for new tokens - no password needed.
Example 2 - login.py
from contextlib import asynccontextmanager from datetime import datetime, timedelta, timezone from typing import Annotated import jwt from fastapi import Depends, FastAPI, HTTPException from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm from pwdlib import PasswordHash from sqlmodel import Field, Session, SQLModel, create_engine, select SECRET_KEY = "45a1456a3ed0187fc7716d558f0c688c48e1e199e89a95b1264ce1f3317c6394" # secrets.token_hex(32) ALGORITHM = "HS256" ACCESS_MINUTES = 15 # short: sent with every request REFRESH_DAYS = 7 # long: sent only to /refresh password_hash = PasswordHash.recommended() DUMMY_HASH = password_hash.hash("not-a-real-password") engine = create_engine("sqlite:///login.db") class User(SQLModel, table=True): id: int | None = Field(default=None, primary_key=True) username: str = Field(unique=True) hashed_password: str class UserPublic(SQLModel): id: int username: str class Tokens(SQLModel): access_token: str refresh_token: str token_type: str = "bearer" class RefreshRequest(SQLModel): refresh_token: str def get_session(): with Session(engine) as session: yield session SessionDep = Annotated[Session, Depends(get_session)] # --- making and reading tokens --- def create_token(user_id: int, kind: str, lifetime: timedelta) -> str: now = datetime.now(timezone.utc) claims = {"sub": str(user_id), "type": kind, "iat": now, "exp": now + lifetime} return jwt.encode(claims, SECRET_KEY, algorithm=ALGORITHM) def issue_tokens(user: User) -> Tokens: return Tokens( access_token=create_token(user.id, "access", timedelta(minutes=ACCESS_MINUTES)), refresh_token=create_token(user.id, "refresh", timedelta(days=REFRESH_DAYS)), ) def read_token(token: str, kind: str) -> int: """The user id from a valid token of this kind - or 401.""" try: claims = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) # signature AND expiry except jwt.InvalidTokenError: # bad signature, expired, garbage, ... raise HTTPException(status_code=401, detail="Invalid or expired token", headers={"WWW-Authenticate": "Bearer"}) if claims.get("type") != kind: # a refresh token is not an access token raise HTTPException(status_code=401, detail="Wrong token type", headers={"WWW-Authenticate": "Bearer"}) return int(claims["sub"]) @asynccontextmanager async def lifespan(app: FastAPI): SQLModel.metadata.drop_all(engine) # a fresh demo database each start SQLModel.metadata.create_all(engine) with Session(engine) as session: session.add(User(username="ravi", hashed_password=password_hash.hash("monsoon2026"))) session.commit() yield app = FastAPI(lifespan=lifespan) oauth2 = OAuth2PasswordBearer(tokenUrl="token") # where /docs logs in # --- 1. log in: username + password -> tokens --- @app.post("/token", response_model=Tokens) def login(form: Annotated[OAuth2PasswordRequestForm, Depends()], session: SessionDep): user = session.exec(select(User).where(User.username == form.username)).first() ok = password_hash.verify(form.password, user.hashed_password if user else DUMMY_HASH) if user is None or not ok: raise HTTPException(status_code=401, detail="Wrong username or password", headers={"WWW-Authenticate": "Bearer"}) return issue_tokens(user) # --- 2. use the access token --- def get_current_user(token: Annotated[str, Depends(oauth2)], session: SessionDep) -> User: user = session.get(User, read_token(token, "access")) if user is None: raise HTTPException(status_code=401, detail="Invalid or expired token", headers={"WWW-Authenticate": "Bearer"}) return user @app.get("/me", response_model=UserPublic) def read_me(user: Annotated[User, Depends(get_current_user)]): return user # --- 3. a new access token, without the password --- @app.post("/refresh", response_model=Tokens) def refresh(data: RefreshRequest, session: SessionDep): user = session.get(User, read_token(data.refresh_token, "refresh")) if user is None: raise HTTPException(status_code=401, detail="Invalid or expired token", headers={"WWW-Authenticate": "Bearer"}) return issue_tokens(user)
try_login.py
from datetime import timedelta from fastapi.testclient import TestClient from login import app, create_token def show(label, r): print(f"{label:<28} -> {r.status_code} {r.text[:75]}") def tamper(token): # change one letter in the middle of the signature i = len(token) - 10 return token[:i] + ("A" if token[i] != "A" else "B") + token[i + 1:] def bearer(token): return {"Authorization": f"Bearer {token}"} with TestClient(app) as c: show("login as JSON", c.post("/token", json={"username": "ravi", "password": "monsoon2026"})) show("wrong password", c.post("/token", data={"username": "ravi", "password": "Monsoon2026"})) r = c.post("/token", data={"username": "ravi", "password": "monsoon2026"}) # a form, like /docs show("login as a form", r) tokens = r.json() show("/me, no token", c.get("/me")) show("/me, access token", c.get("/me", headers=bearer(tokens["access_token"]))) show("/me, one letter changed", c.get("/me", headers=bearer(tamper(tokens["access_token"])))) show("/me, expired token", c.get("/me", headers=bearer(create_token(1, "access", timedelta(minutes=-1))))) show("/me, refresh token", c.get("/me", headers=bearer(tokens["refresh_token"]))) show("/refresh, refresh token", c.post("/refresh", json={"refresh_token": tokens["refresh_token"]})) show("/refresh, access token", c.post("/refresh", json={"refresh_token": tokens["access_token"]}))
Output
login as JSON -> 422 {"detail":[{"type":"missing","loc":["body","username"],"msg":"Field require wrong password -> 401 {"detail":"Wrong username or password"} login as a form -> 200 {"access_token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxIiwidHlwZ /me, no token -> 401 {"detail":"Not authenticated"} /me, access token -> 200 {"id":1,"username":"ravi"} /me, one letter changed -> 401 {"detail":"Invalid or expired token"} /me, expired token -> 401 {"detail":"Invalid or expired token"} /me, refresh token -> 401 {"detail":"Wrong token type"} /refresh, refresh token -> 200 {"access_token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxIiwidHlwZ /refresh, access token -> 401 {"detail":"Wrong token type"}

Reading the output

  • login as JSON - 422 "missing username". OAuth2 says the login is a FORM (application/x-www-form-urlencoded). In TestClient that is data=, not json=.
  • wrong password - 401 with the same message as an unknown user (Lesson 6.2).
  • login as a form - 200 with access_token, refresh_token and token_type "bearer".
  • /me with no token - 401 "Not authenticated", from OAuth2PasswordBearer before our code ran.
  • one letter changed, and expired - both 401 "Invalid or expired token". We do not tell which; the client logs in again either way.
  • A refresh token at /me, and an access token at /refresh - both 401 "Wrong token type".

Inside the two tokens

We decoded the tokens from one login (without checking, just to look):

  • Both say sub "1". Only type and the lifetime differ: 900 seconds (15 minutes) and 604,800 seconds (7 days).
  • The answer also had token_type "bearer" - the client puts that word in front of the token.
Output - each token through jwt.decode(token, options={"verify_signature": False}), then exp - iat
access_token {'sub': '1', 'type': 'access', 'iat': 1794747165, 'exp': 1794748065} lifetime (s): 900 refresh_token {'sub': '1', 'type': 'refresh', 'iat': 1794747165, 'exp': 1795351965} lifetime (s): 604800

Why two tokens?

  • A signed token cannot be taken back. If an access token is stolen, it works until it expires - so make that short.
  • But a 15-minute token alone would make users log in four times an hour.
  • So the client also gets a refresh token. It is sent ONLY to /refresh - not with every request - so it is seen far less often, and is harder to steal.
  • When /me answers 401, the client calls /refresh, gets new tokens, and tries again. The user sees nothing.
  • Because /refresh looks the user up, that is where you can say no: a deleted user gets 401. Lesson 6.4 goes further and checks the user on every request.

The same login with curl

We ran uvicorn login:app --port 8163 and logged in from a terminal:

  • curl -d sends a form - exactly what /token wants.
  • The token goes in the Authorization header, after the word Bearer and one space.
  • Without a token: 401 and www-authenticate: Bearer - the standard hint "send a Bearer token".
Output - curl (token shortened)
$ curl -s -X POST localhost:8163/token -d "username=ravi&password=monsoon2026" {"access_token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxIiwidHlwZSI6ImFjY2VzcyIsImlhdCI6MTc5NDc0NzE2 ... $ curl -s localhost:8163/me -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIs..." {"id":1,"username":"ravi"} $ curl -si localhost:8163/me # no token HTTP/1.1 401 Unauthorized www-authenticate: Bearer {"detail":"Not authenticated"}

Leak 1: a bad token crashed the server

Our first version (login_v1.py) caught only the error we had thought of - an expired token. leaks.py sent three bad tokens to both versions:

  • Before: one changed letter - 500 Internal Server Error. The word "hello" - 500 too. jwt.decode raised InvalidSignatureError and DecodeError, and nothing caught them.
  • The server log showed: jwt.exceptions.DecodeError: Not enough segments. A 500 is a crash: it fills your error alerts, and it tells attackers they found a weak spot.
  • The fix: catch jwt.InvalidTokenError - the parent of every PyJWT token error: bad signature, expired, wrong algorithm, garbage.
  • After: 401 for all of them.
The first version (login_v1.py)
try: claims = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) # signature AND expiry except jwt.ExpiredSignatureError: # only the error we thought of raise HTTPException(status_code=401, detail="Invalid or expired token", headers={"WWW-Authenticate": "Bearer"}) return int(claims["sub"]) # no type check
Output - the server log (login_v1, last lines)
raise DecodeError("Not enough segments") from err jwt.exceptions.DecodeError: Not enough segments

Leak 2: the refresh token worked everywhere

login_v1.py also had no type check. Both tokens were signed with the same key and both had a sub - so /me accepted either:

  • Before: the 7-day refresh token opened /me - 200. A stolen refresh token was a 7-day access token, and the short access token protected nothing.
  • The fix: a "type" claim when making tokens, and read_token(token, "access") or read_token(token, "refresh") when checking them.
  • After: 401 "Wrong token type", in both directions.
leaks.py
import importlib import sys from fastapi.testclient import TestClient app = importlib.import_module(sys.argv[1]).app def me(c, token): r = c.get("/me", headers={"Authorization": f"Bearer {token}"}) return f"{r.status_code} {r.text[:60]}" with TestClient(app, raise_server_exceptions=False) as c: # see a 500 the way a real client does print(sys.argv[1]) tokens = c.post("/token", data={"username": "ravi", "password": "monsoon2026"}).json() access, refresh = tokens["access_token"], tokens["refresh_token"] i = len(access) - 10 tampered = access[:i] + ("A" if access[i] != "A" else "B") + access[i + 1:] print(" /me, one letter changed ->", me(c, tampered)) print(" /me, not a token at all ->", me(c, "hello")) print(" /me, the 7-day refresh token ->", me(c, refresh))
Output - python leaks.py login_v1, then login
login_v1 /me, one letter changed -> 500 Internal Server Error /me, not a token at all -> 500 Internal Server Error /me, the 7-day refresh token -> 200 {"id":1,"username":"ravi"} login /me, one letter changed -> 401 {"detail":"Invalid or expired token"} /me, not a token at all -> 401 {"detail":"Invalid or expired token"} /me, the 7-day refresh token -> 401 {"detail":"Wrong token type"}

Logging in from /docs

  • Run fastapi dev login.py and open /docs. Click Authorize: a form asks for username and password.
  • It posts them to tokenUrl ("token") as a form, keeps the access_token, and sends it with every "Try it out".
  • The form has more fields - grant_type, scope, client_id, client_secret - from the OAuth2 standard. Only username and password are required; leave the rest empty.
  • In the schema: /token takes application/x-www-form-urlencoded, and every route that uses oauth2 shows a lock.

Login and JWT at a glance

Make a token

sub as a string; exp as a datetime.

jwt.encode({"sub": str(user.id), "exp": exp}, SECRET_KEY, algorithm="HS256")
Check a token

Signature and expiry. One algorithm.

jwt.decode(token, SECRET_KEY, algorithms=["HS256"])
Any bad token

The parent of all token errors -> 401.

except jwt.InvalidTokenError:
Login form

username and password as a form.

form: Annotated[OAuth2PasswordRequestForm, Depends()]
Login answer

What OAuth2 clients expect.

{"access_token": token, "token_type": "bearer"}
Read the token

401 if missing; /docs login.

oauth2 = OAuth2PasswordBearer(tokenUrl="token")
A key

32 bytes or more, from the server only.

python -c "import secrets; print(secrets.token_hex(32))"

Try it yourself

The code does not change. Swap the content string and the program does something else entirely.

Read a token

“Log in through /docs, copy the access_token from the answer, and paste it into jwt.decode(token, options={"verify_signature": False}). Which claims do you see?”

Change the key

“Log in, then change one character of SECRET_KEY and restart. Does the old token still work? What does that tell you about changing the key?”

One-minute tokens

“Set ACCESS_MINUTES = 1, log in, wait a minute, and call /me. Then use /refresh.”

Leeway

“Try jwt.decode(expired_token, SECRET_KEY, algorithms=["HS256"], leeway=120) on a token that expired one minute ago. Why might servers with slightly different clocks need this?”

What usually goes wrong

Catching only ExpiredSignatureError

A changed or garbage token crashed with 500. Catch jwt.InvalidTokenError.

✗ except jwt.ExpiredSignatureError:
✓ except jwt.InvalidTokenError:
One kind of token for everything

The 7-day refresh token worked at /me. Add a "type" claim and check it.

Sending the login as JSON

OAuth2PasswordRequestForm wants a form - 422 "missing username" for JSON.

✗ c.post("/token", json={...})
✓ c.post("/token", data={...})
Putting secrets in the token

Anyone can read the payload - we decoded it without the key.

Leaving out algorithms=

Always list the one algorithm you sign with. It stops alg "none" tokens.

✗ jwt.decode(token, SECRET_KEY)
✓ jwt.decode(token, SECRET_KEY, algorithms=["HS256"])
A short or shared secret key

PyJWT warned below 32 bytes. Make one with secrets.token_hex(32), and keep it out of git (Lesson 8.2).

Long-lived access tokens

A stolen access token works until exp. Keep it to minutes, and use a refresh token for the rest.

Best practices

  • Check tokens in ONE function, and turn every token error into 401.
  • Put only what you need in a token: sub, type, iat, exp.
  • Short access tokens (minutes), longer refresh tokens (days), each with a type.
  • Sign with one algorithm and always pass algorithms=[...].
  • A random key of 32+ bytes, from the environment, never in git.
  • Send tokens only over HTTPS (Lesson 10.3) - anyone who sees one can use it.

Practice

Write these yourself before opening anything. Getting them wrong first is most of how this sticks.

1.

Add "expires_in" (seconds) to the /token answer, as many OAuth2 clients expect it. Then write a small client loop: call /me, and on 401 call /refresh once and retry.

Show hint

expires_in = ACCESS_MINUTES * 60. Add it to the Tokens model with a default.

2.

Add an "iss" (issuer) claim, "todo-api", and make read_token refuse tokens from any other issuer. Test it with a token made with the right key but iss "other-api".

Show hint

jwt.decode(..., issuer="todo-api") checks it for you and raises InvalidIssuerError - a child of InvalidTokenError.

Coding challenge

Refresh tokens that work only once

If a refresh token is stolen, the thief can use it for 7 days. Make each refresh token single-use, so a copied token is noticed.

It should
  • Give each refresh token a random "jti" (token id), with secrets.token_urlsafe(16).
  • Store used jti values in a table. /refresh refuses a jti it has already seen.
  • Each /refresh returns a NEW refresh token (rotation).
  • Show with TestClient: the first /refresh works, the same token a second time gives 401.

Key points

  • Log in once with a form; send Authorization: Bearer <token> after that.
  • A JWT is header.payload.signature - readable by anyone, changeable by no one without the key.
  • jwt.decode checks the signature and the expiry; pass algorithms=[...].
  • except jwt.InvalidTokenError catches every bad token - no more 500s.
  • A "type" claim keeps refresh tokens out of normal routes.
  • OAuth2PasswordRequestForm + OAuth2PasswordBearer give /docs a working login.

Quick check before you move on

How many parts does a JWT have, and which can anyone read?
Three - header, payload, signature. The header and payload are plain base64.
What did /token answer for a login sent as JSON?
422 - username missing, because it expects a form.
What did login_v1 answer for the token "hello"?
500 Internal Server Error - DecodeError was not caught.
How long were the access and refresh tokens valid?
900 seconds (15 minutes) and 604,800 seconds (7 days).

Interview questions

Explain how JWT authentication works in a FastAPI app.

The client posts credentials to a token endpoint (OAuth2 password form); the server verifies the password hash and returns a signed, short-lived access token, often with a refresh token. The client sends it as a Bearer header; a dependency (OAuth2PasswordBearer plus jwt.decode with a fixed algorithm list) verifies signature and expiry, maps any InvalidTokenError to 401, and loads the user from the sub claim.

What are the main risks with JWTs, and how do you handle them?

They cannot be revoked before expiry (short lifetimes, refresh tokens, a user or token-version check, deny lists by jti); payloads are readable (no sensitive data); algorithm confusion and alg none (pin algorithms); weak or leaked keys (long random keys from a secret store, rotation); token theft (HTTPS, careful storage on the client, rotating single-use refresh tokens).

HS256 or RS256?

HS256 uses one shared secret to sign and verify - simple when one service does both. RS256 signs with a private key and verifies with a public key, so other services can verify tokens without being able to make them - better when many services check tokens from one auth server.

Quiz

  1. 1.

    Why can the server trust a JWT without storing it?

  2. 2.

    Why is a short access token not enough on its own?

  3. 3.

    What does the "type" claim stop?

Comments

Sign in to leave a comment. Your name and photo come from Google; nothing else is shared.

Loading comments...