Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 50 ยท Authentication and security

OAuth2 password flow and JWT

Build FastAPI login with OAuth2PasswordBearer and signed JWT access tokens: token endpoint, HS256 signing, expiry, a current-user dependency and refresh tokens.

After a user logs in, the browser or app needs a way to prove who it is on every later request without sending the password each time. The usual answer is a token: a short string the server hands out at login and the client sends back in an Authorization header.

FastAPI has first-class support for the OAuth2 "password flow" (username and password exchanged for a token) and its docs page even gets a working Authorize button. In this lesson you will build the token endpoint, create and verify signed JWT tokens, protect endpoints with a get_current_user dependency, handle expiry, and see how refresh tokens fit in.

The password flow in four steps

Log in POST username and password to /token.
Get a token The server returns a signed access token.
Send it Authorization header with the Bearer token.
Server checks Signature and expiry are verified.
1 / 2
sequenceDiagram
    participant C as Client
    participant A as API
    C->>A: POST /token (username, password)
    A-->>C: access_token
    C->>A: GET /me + Bearer token
    A->>A: verify signature and exp
    A-->>C: 200 user data

One login, then the token travels with each request.

What a JWT looks like

A JSON Web Token has three parts separated by dots: header.payload.signature.

  • The header names the algorithm, for example {"alg": "HS256", "typ": "JWT"}.
  • The payload holds claims: sub (subject, usually the user id), exp (expiry time as a Unix timestamp), maybe iat (issued at) or a role.
  • The signature is an HMAC over the first two parts using a secret only the server knows.

Header and payload are only Base64url-encoded, not encrypted: anyone can read them. The signature does not hide data; it proves nobody changed it. So never put secrets in a JWT, and keep the signing key private. If the payload is altered, the signature no longer matches and the server rejects the token.

In production you would use a library such as PyJWT:

Python
# Read-only: pip install pyjwt
import jwt
from datetime import datetime, timedelta, timezone

token = jwt.encode(
    {"sub": "ada", "exp": datetime.now(timezone.utc) + timedelta(minutes=15)},
    SECRET_KEY,
    algorithm="HS256",
)
claims = jwt.decode(token, SECRET_KEY, algorithms=["HS256"])   # raises on bad or expired

PyJWT is not available in the browser runner, and writing the HS256 steps by hand is the best way to understand them. The next example does so with only hmac and base64. This is a teaching stand-in: use PyJWT in real code.

Python Create, verify and tamper with an HS256 token

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The valid token verifies and its payload is plainly readable. The same token fails once its exp has passed, and the forged payload fails because the signature no longer matches. Without the secret, an attacker cannot produce a valid signature for new claims.

OAuth2PasswordBearer and the token endpoint

FastAPI provides two helpers in fastapi.security:

  • OAuth2PasswordRequestForm is a dependency that reads the standard username and password form fields (form-encoded, not JSON; that is what the OAuth2 spec says). It needs the python-multipart package.
  • OAuth2PasswordBearer(tokenUrl="token") is a dependency that reads the Authorization: Bearer ... header and returns the token string, or answers 401 with a WWW-Authenticate: Bearer header if it is missing. It also tells the OpenAPI docs where the login endpoint is, which is what makes the Authorize button work.

On top of those you write two pieces: the /token endpoint that checks credentials and issues the token, and a get_current_user dependency that turns a token into a user. Any endpoint that depends on get_current_user is protected, following the pattern from Dependencies.

Python Login, protected endpoint and expiry

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Check each line of the output against the code: with no header the OAuth2PasswordBearer dependency itself answers 401 Not authenticated before your function runs; a wrong password gives 400; a good login returns the bearer token; the token opens /me; an hour-old token and a garbage token both end in your own 401.

Details worth copying into real projects:

  • Return 401 with the WWW-Authenticate: Bearer header for invalid credentials on protected endpoints. The OAuth2 password form itself traditionally uses 400 for a bad username/password.
  • Store the user id (not the email or the whole profile) in sub, and load the current user from the database in the dependency, so deleted or disabled users lose access at once.
  • Read the secret from environment settings (Settings and configuration); generate it with openssl rand -hex 32. Always pass an explicit algorithms=[...] list when decoding with PyJWT.
  • Serve over HTTPS only. A bearer token works for whoever holds it.

Expiry and refresh tokens

Short-lived access tokens (5 to 30 minutes) limit the damage if one leaks, but forcing a login every 15 minutes is unfriendly. The usual design uses two tokens:

Token Lifetime Sent to Purpose
Access token minutes every API request Prove identity
Refresh token days or weeks only /refresh Get a new access token

When the access token expires, the client posts the refresh token to /refresh and receives a new access token (and often a new refresh token, rotating it so the old one stops working). Refresh tokens are best stored server-side (a database row you can delete) or as an opaque random string, so you can revoke them at logout. A pure self-contained JWT cannot be revoked before it expires, which is another reason to keep access tokens short.

Python
# Read-only sketch of a refresh endpoint
@app.post("/refresh")
async def refresh(body: RefreshRequest, db: DbDep):
    record = await find_refresh_token(db, body.refresh_token)
    if record is None or record.revoked or record.expires_at < now():
        raise HTTPException(status_code=401, detail="Invalid refresh token")
    await revoke(db, record)                           # rotation
    return await issue_token_pair(db, record.user_id)  # new access + refresh

Where the browser keeps tokens matters too: localStorage is readable by any script on your page (XSS), while an HttpOnly cookie is not but needs CSRF protection. Pick deliberately; for traditional web apps cookies are often safer.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the signature part of a JWT provide?

    The payload is only Base64url-encoded, so anyone can read it. The HMAC signature detects tampering.
  2. 2. What does OAuth2PasswordBearer(tokenUrl="token") do when the Authorization header is missing?

    It is a dependency that extracts the Bearer token and rejects requests without one. It also tells the docs where to log in.
  3. 3. Which claim holds the expiry time?

    exp is the expiry Unix timestamp. sub is the subject and iat is when it was issued.
  4. 4. Why use short-lived access tokens plus refresh tokens?

    Short access tokens limit damage; the refresh token (checked server-side and revocable) renews them without a new login.
  5. 5. What should you store in the sub claim?

    Put an id in sub and load the user from storage in get_current_user, so disabled or deleted users lose access immediately.

Summary

  • A JWT is header.payload.signature; the payload is readable, the signature protects against changes.
  • OAuth2PasswordRequestForm reads the login form; OAuth2PasswordBearer extracts the Bearer token and powers the docs' Authorize button.
  • A /token endpoint checks credentials and returns access_token and token_type: "bearer".
  • A get_current_user dependency verifies signature and exp, loads the user and raises 401 with WWW-Authenticate: Bearer otherwise.
  • Keep access tokens short and use revocable, rotating refresh tokens for longer sessions.
  • Use PyJWT (and HTTPS and environment secrets) in real code; the hmac version here is a teaching stand-in.

Next: control what each user may do in Roles, scopes and permissions.