DEV Community

Cover image for Add JWT Authentication to FastAPI
Muhammad Saud
Muhammad Saud

Posted on Originally published at logicstack.org

Add JWT Authentication to FastAPI

JWT authentication protects an API with signed tokens. A user logs in once, receives a token, and sends it with every later request. The server checks the signature instead of looking up a session, so the API stays stateless. In this tutorial we add that flow to a FastAPI notes API and test the failure cases and the happy path.

Key takeaways

  • FastAPI ships OAuth2 helpers, and the current official pattern pairs them with pwdlib for password hashing and PyJWT for token signing.

  • Passwords are stored as Argon2 hashes, never as plain text, and the hash is verified with a timing safe check.

  • A JWT carries a subject claim and an expiry time, and changing one character in the token breaks its signature.

  • One dependency, get_current_user, protects any route, so adding auth to a new endpoint is a single line.

  • Testing caught a real leak in our first version: the profile endpoint returned the password hash. We fixed it before publishing.

How does JWT authentication work?

The flow has three parts. First, the client sends a username and password to a login endpoint. The server checks the password against the stored hash and, if it matches, signs a JSON Web Token with a secret key. The token has three parts, header, payload, and signature, joined by dots. Second, the client sends the token in an Authorization header as Bearer token on every protected request. Third, the server decodes the token with the same secret, checks the signature and the expiry time, and reads the subject claim to learn who is calling. A JWT is signed, not encrypted, so anyone holding it can read the payload. Never put secrets inside a token. The signature only proves that nobody changed the payload after the server signed it.

What we build

We build a small notes API in a single file, main.py. It has a register endpoint that creates a user with a hashed password, a token endpoint that logs a user in, a profile endpoint that returns the current user, and two protected notes endpoints that create and list notes for the logged in user only. Users and notes live in memory dictionaries, so the example runs with no database setup. We also write a test script that drives the whole flow and prints the real responses, including the four failure cases most guides skip.

Prerequisites

You need Python 3.10 or newer and a basic grasp of FastAPI routes and Pydantic models. We tested with Python 3.12.3, FastAPI 0.162.2, PyJWT 2.15.1, pwdlib 0.4.2, python-multipart 0.0.34, and Uvicorn 0.54.0. All commands below run in a virtual environment.

Step 1: Install the packages

FastAPI needs three extra packages for this tutorial. PyJWT signs and verifies the tokens. pwdlib hashes the passwords with Argon2, which the FastAPI docs recommend. python-multipart lets the login endpoint read form data, because the OAuth2 password flow sends the username and password as a form, not as JSON.

pip install fastapi uvicorn pyjwt "pwdlib[argon2]" python-multipart
Enter fullscreen mode Exit fullscreen mode

The install output confirms the versions we tested with: PyJWT 2.15.1, pwdlib 0.4.2, and python-multipart 0.0.34. Note that FastAPI moved away from passlib and python-jose. Those two packages appear in most older tutorials, but passlib has had no real maintenance for years, and the official FastAPI docs now use pwdlib and PyJWT. Following an old tutorial here is how many projects end up with unmaintained auth code.

Step 2: Hash passwords with Argon2

We never store a plain text password. We store an Argon2 hash and check a login attempt against it. Create the hasher once at the top of main.py, then add two small helpers.

from pwdlib import PasswordHash

password_hash = PasswordHash.recommended()

def get_password_hash(password: str) -> str:
    return password_hash.hash(password)

def verify_password(plain_password: str, hashed_password: str) -> bool:
    return password_hash.verify(plain_password, hashed_password)
Enter fullscreen mode Exit fullscreen mode

PasswordHash.recommended() picks Argon2id with sensible defaults. A hash looks like $argon2id$v=19$m=65536,t=3,p=4$... and it already contains the salt and the cost settings, so verification needs only the password and the stored hash. Hashing is deliberately slow, which is what makes a stolen database hard to crack.

Step 3: Issue tokens with PyJWT

The token carries two claims: sub, the username of the person who logged in, and exp, the time after which the token stops working. We set the lifetime to 30 minutes. The secret key signs the token, and PyJWT warns when an HMAC key is shorter than 32 bytes, so our development secret is a 64 character hex string. In production the secret must come from an environment variable, never from source code.

import os
from datetime import UTC, datetime, timedelta
import jwt

SECRET_KEY = os.environ.get("SECRET_KEY", "dev-only-secret-change-me-...")
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30

def create_access_token(data: dict, expires_delta: timedelta | None = None) -> str:
    to_encode = data.copy()
    expire = datetime.now(UTC) + (expires_delta or timedelta(minutes=15))
    to_encode.update({"exp": expire})
    return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
Enter fullscreen mode Exit fullscreen mode

HS256 means the token is signed with one shared secret using HMAC and SHA-256. That is the right choice for a single API that both issues and checks its own tokens. If a separate service needs to verify tokens without holding the secret, use an asymmetric algorithm such as RS256 instead.

Step 4: Verify tokens in a dependency

FastAPI dependency injection does the heavy lifting here. OAuth2PasswordBearer reads the Bearer token from the Authorization header, and our get_current_user dependency decodes it, checks the signature and expiry, and loads the user. Every protected route then takes the current user as a parameter.

from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from jwt.exceptions import InvalidTokenError

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]) -> User:
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": "Bearer"},
    )
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        username = payload.get("sub")
        if username is None:
            raise credentials_exception
        token_data = TokenData(username=username)
    except InvalidTokenError:
        raise credentials_exception
    user = get_user(token_data.username)
    if user is None:
        raise credentials_exception
    return User(**user.model_dump(exclude={"hashed_password"}))
Enter fullscreen mode Exit fullscreen mode

Three details matter here. First, jwt.decode raises InvalidTokenError for a bad signature and for an expired token, and both cases become the same 401 response, so an attacker learns nothing about which check failed. Second, the WWW-Authenticate header tells the client that a Bearer token is expected. Third, we return the plain User model, never the database model that holds the hash. That last line is there because our test caught a leak, and step 8 shows what happened.

Step 5: Add register and login

The register endpoint hashes the password before storing anything. A duplicate username gets a 409, which is the correct status for a conflict with existing state. The login endpoint takes form data through OAuth2PasswordRequestForm, checks the credentials, and returns the token. A wrong username or password gets the same 401 either way, so the response never reveals whether the username exists.

@app.post("/register", status_code=status.HTTP_201_CREATED)
def register(user: UserCreate):
    if user.username in users_db:
        raise HTTPException(status_code=409, detail="Username already taken")
    users_db[user.username] = {
        "username": user.username,
        "email": user.email,
        "full_name": user.full_name,
        "hashed_password": password_hash.hash(user.password),
    }
    notes_db[user.username] = []
    return {"username": user.username, "email": user.email}

@app.post("/token")
def login_for_access_token(
    form_data: Annotated[OAuth2PasswordRequestForm, Depends()],
) -> Token:
    user = authenticate_user(form_data.username, form_data.password)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Incorrect username or password",
            headers={"WWW-Authenticate": "Bearer"},
        )
    access_token = create_access_token(
        data={"sub": user.username},
        expires_delta=timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES),
    )
    return Token(access_token=access_token, token_type="bearer")
Enter fullscreen mode Exit fullscreen mode

One more timing detail lives in authenticate_user. When the username does not exist, we still run a password verification against a dummy hash before returning False. Without that step, a wrong username answers faster than a wrong password, and that timing difference leaks which usernames exist.

Step 6: Protect the notes routes

Protecting a route is one parameter: current_user: Annotated[User, Depends(get_current_user)]. FastAPI runs the dependency before the route body, so an unauthenticated request never reaches our code. Notes are stored per user, so each user only ever sees their own list.

@app.get("/users/me")
def read_users_me(current_user: Annotated[User, Depends(get_current_user)]):
    return current_user

@app.post("/notes", status_code=status.HTTP_201_CREATED)
def create_note(note: NoteCreate, current_user: Annotated[User, Depends(get_current_user)]):
    stored = {"id": len(notes_db[current_user.username]) + 1, **note.model_dump()}
    notes_db[current_user.username].append(stored)
    return stored

@app.get("/notes")
def list_notes(current_user: Annotated[User, Depends(get_current_user)]):
    return notes_db[current_user.username]
Enter fullscreen mode Exit fullscreen mode

Start the server with uvicorn main:app and open http://127.0.0.1:8000/docs. The login endpoint appears in the Swagger UI with an Authorize button, because OAuth2PasswordBearer describes the security scheme in the OpenAPI document. You can log in and call the protected routes from the browser.

Step 7: Run the test and read the real output

We wrote a test script with FastAPI TestClient that drives the whole flow. It registers a user, logs in, creates a note, and then tries the four failure cases. Here is the real output from our run.

== 1. Register alice ==
201 {'username': 'alice', 'email': 'alice@example.com'}
== 2. Register alice again (duplicate) ==
409 {'detail': 'Username already taken'}
== 3. Log in with the right password ==
200 {'access_token': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ...', 'token_type': 'bearer'}
decoded payload: {'sub': 'alice', 'exp': 1795058560}
== 4. Log in with the wrong password ==
401 {'detail': 'Incorrect username or password'}
== 5. GET /users/me with no token ==
401 {'detail': 'Not authenticated'}
== 6. GET /users/me with the token ==
200 {'username': 'alice', 'email': 'alice@example.com', 'full_name': 'Alice Example'}
== 7. Create and list a note with the token ==
201 {'id': 1, 'title': 'First note', 'body': 'JWT auth works.'}
200 [{'id': 1, 'title': 'First note', 'body': 'JWT auth works.'}]
Enter fullscreen mode Exit fullscreen mode

The token is shown shortened here. Decoding it shows the payload plainly: the subject is alice and exp is the expiry as a Unix timestamp. That is the point of the earlier warning. A token is readable by anyone who holds it, so it carries only the username and the expiry, nothing sensitive.

What happens when a token is wrong or expired?

This is the part most tutorials skip, and it is the part that decides whether your auth actually works. We tested three broken tokens against the protected profile route.

== 8. Tampered token (last char changed) ==
401 {'detail': 'Could not validate credentials'}
== 9. Expired token (issued with -1 minute expiry) ==
401 {'detail': 'Could not validate credentials'}
== 10. /docs is reachable ==
200
Enter fullscreen mode Exit fullscreen mode

Changing one character at the end of the token breaks the signature, and PyJWT rejects it. A token issued with an expiry in the past is rejected the same way. Both return the same 401, so a caller cannot tell a bad signature from an expired token. We also ran the app on a real Uvicorn server and confirmed the same behaviour over HTTP: the docs page returned 200, registration returned 201, and the profile route returned 200 with a valid token.

Step 8: The bug our test caught

Our first version of get_current_user returned the database user object directly, and the test output showed the problem at once. The profile response contained the Argon2 hash next to the username and email. A hash is not a password, but it does not belong in an API response, and returning it hands an attacker the exact string to crack offline. The fix is one line: rebuild the plain User model without the hash before returning, as shown in step 4. After the fix, the same test returned 200 with only the username, email, and full name.

What to try next

First, move the users and notes into a real database. Our in-memory dictionaries vanish on restart, and the same code works with a SQLite table plus a small change to get_user. Second, add refresh tokens. A 30 minute access token is good practice, but logging users in every half hour is a poor experience, so issue a long lived refresh token and a short lived access token, then add an endpoint that trades one for the other. Third, add role based access. Give the user model a role field, write a second dependency that checks it, and protect an admin route with it. The pattern is the same dependency trick, and it composes cleanly with what we built here.


Originally published on LogicStack. Run the code examples right in your browser with our free interactive Python and SQL playgrounds — no setup, no sign-up.

Top comments (0)