Skip to main content

APIs · Intermediate · 25 min

How to Add JWT Authentication to a FastAPI API

By Padding · Updated 16 Nov 2026
FastAPI 0.163 · Python 3.15 · PyJWT 2.15 · pwdlib 0.4

You will add login to a FastAPI 0.163 API on Python 3.15 with Argon2 password hashes, PyJWT access tokens that expire after 15 minutes, a signing secret kept out of your code, a protected route, and tests that prove expired, tampered and unsigned tokens are refused.

On this page

Authentication answers one question on every request: who is calling? With a JSON Web Token (JWT), your API answers it once, at login. It checks the password, then hands the client a short signed token. The client sends that token back in an Authorization header, and the API verifies the signature instead of looking anyone up. A JWT is three base64url parts: a header, a payload of claims such as sub (the user) and exp (the expiry time), and a signature made with a secret only your server knows. The payload is signed, not encrypted: anyone who holds the token can read it, so never put secrets in it.

This tutorial adds login to a small FastAPI app. Its libraries are the ones the FastAPI documentation uses for this job: PyJWT for tokens and pwdlib with Argon2 for password hashes. The choices that matter for safety are made explicit: passwords are stored only as Argon2 hashes, the signing secret comes from the environment, tokens last 15 minutes, exp and sub are required, and the accepted algorithm is pinned so a token that says alg: none is refused. FastAPI's own guide is at https://fastapi.tiangolo.com/tutorial/security/oauth2-jwt/.

Step 1 · Create the project

Make a folder and add FastAPI, the two libraries and the test tools. The version range lets patch releases of FastAPI 0.163 in:

Bash
mkdir -p ~/jwt-api
cd ~/jwt-api
uv init --no-package
uv add "fastapi[standard]>=0.163,<0.164" PyJWT "pwdlib[argon2]"
uv add --dev pytest httpx

fastapi[standard] includes python-multipart, which FastAPI needs to read the login form.

Check it worked

Bash
uv run python -c "import jwt, pwdlib; print('PyJWT', jwt.__version__)"

The output is PyJWT 2.15.1, or a later 2.x release.

Step 2 · Create the signing secret

The secret signs every token. Anyone who learns it can forge a login for any user, so it must never appear in your code, your Git history or a command line. Generate it straight into a file that only you can read. umask 077 makes new files private from the moment they exist:

Bash
cd ~/jwt-api
(umask 077; printf 'JWT_SECRET=%s\n' "$(openssl rand -hex 32)" > .env)
ls -l .env

The listing starts with -rw-------. The key is 64 hex characters, which is 256 bits, the size HS256 expects. If your project is in Git, add .env to .gitignore before the first commit: see keep secrets out of Git.

Your server reads the secret from the JWT_SECRET environment variable. uv run --env-file .env loads the file for one command. On a production server, put the same line in a file that only the service can read and pass it to systemd with EnvironmentFile=, as in run your app as a systemd service.

Step 3 · Create a user with a hashed password

A real API keeps users in a database. To stay focused on the login, this one keeps them in a JSON file. The script below asks for a password, hashes it with Argon2id and stores only the hash. The prompt means the password never lands in your shell history. The file is created private from the start:

Bash
cd ~/jwt-api
cat > create_user.py <<'PY'
import getpass
import json
import os
import sys
from pathlib import Path

from pwdlib import PasswordHash

USERS_FILE = Path(os.environ.get("USERS_FILE", "users.json"))

username = sys.argv[1]
password = getpass.getpass(f"Password for {username}: ")
if len(password) < 12:
    sys.exit("Use at least 12 characters.")

users = json.loads(USERS_FILE.read_text()) if USERS_FILE.exists() else {}
users[username] = PasswordHash.recommended().hash(password)

fd = os.open(USERS_FILE, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(fd, "w") as f:
    json.dump(users, f, indent=2)
print(f"Saved {username} to {USERS_FILE}")
PY

PasswordHash.recommended() returns a hasher that uses Argon2id with the library's current recommended parameters. Each hash carries its own random salt and its settings, so you can raise the cost later and still verify old hashes.

Run it for a user called alice. Type a password of 12 or more characters when prompted:

Bash
uv run python create_user.py alice

Check it worked

Bash
cd ~/jwt-api
ls -l users.json
cut -c1-40 users.json

The file is private (-rw-------) and the hash starts with "alice": "$argon2id$v=19$m=65536,t=3,p=4$. The password itself is nowhere in the file.

Step 4 · Write the API

Write the whole app in one file, then read the notes under it:

Bash
cd ~/jwt-api
cat > main.py <<'PY'
import json
import os
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Annotated

import jwt
from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from pwdlib import PasswordHash
from pydantic import BaseModel

SECRET_KEY = os.environ["JWT_SECRET"]
ALGORITHM = "HS256"
ACCESS_TOKEN_MINUTES = 15
USERS_FILE = Path(os.environ.get("USERS_FILE", "users.json"))

password_hash = PasswordHash.recommended()
DUMMY_HASH = password_hash.hash("a password nobody has")

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
app = FastAPI(title="JWT demo")


class Token(BaseModel):
    access_token: str
    token_type: str


class User(BaseModel):
    username: str


def load_users() -> dict[str, str]:
    return json.loads(USERS_FILE.read_text())


def authenticate(username: str, password: str) -> User | None:
    stored = load_users().get(username)
    if stored is None:
        password_hash.verify(password, DUMMY_HASH)  # same work for unknown users
        return None
    if not password_hash.verify(password, stored):
        return None
    return User(username=username)


def create_access_token(username: str) -> str:
    now = datetime.now(timezone.utc)
    claims = {
        "sub": username,
        "iat": now,
        "exp": now + timedelta(minutes=ACCESS_TOKEN_MINUTES),
    }
    return jwt.encode(claims, SECRET_KEY, algorithm=ALGORITHM)


def current_user(token: Annotated[str, Depends(oauth2_scheme)]) -> User:
    unauthorized = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Invalid or expired token",
        headers={"WWW-Authenticate": "Bearer"},
    )
    try:
        claims = jwt.decode(
            token,
            SECRET_KEY,
            algorithms=[ALGORITHM],
            options={"require": ["exp", "sub"]},
        )
    except jwt.InvalidTokenError:
        raise unauthorized
    username = claims["sub"]
    if username not in load_users():
        raise unauthorized
    return User(username=username)


@app.post("/token")
def login(form: Annotated[OAuth2PasswordRequestForm, Depends()]) -> Token:
    user = authenticate(form.username, form.password)
    if user is None:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Incorrect username or password",
            headers={"WWW-Authenticate": "Bearer"},
        )
    return Token(access_token=create_access_token(user.username), token_type="bearer")


@app.get("/users/me")
def read_me(user: Annotated[User, Depends(current_user)]) -> User:
    return user


@app.get("/health")
def health():
    return {"status": "ok"}
PY
  • SECRET_KEY = os.environ["JWT_SECRET"] stops the app at startup if the secret is missing, instead of signing tokens with an empty key.
  • authenticate runs a hash check against a dummy hash when the username is unknown. A login for a missing user then takes about as long as one for a real user, so response time does not reveal which usernames exist. Both failures give the same message.
  • create_access_token sets sub, the issue time iat and the expiry exp, 15 minutes ahead. PyJWT accepts datetime values and converts them to the numeric timestamps the standard requires.
  • jwt.decode is given algorithms=[ALGORITHM]. Never read the algorithm from the token's own header: a list that you control is what stops an attacker choosing none or a weaker algorithm. options={"require": [...]} rejects tokens that lack exp or sub, and PyJWT checks exp on its own. Every failure is a subclass of jwt.InvalidTokenError, so one except covers a bad signature, a bad format and an expired token. The caller gets the same 401 for all of them.
  • current_user also checks that the user still exists, so deleting a user stops their tokens working before they expire.

Start the server in a second terminal. --env-file .env loads the secret:

Bash
cd ~/jwt-api
uv run --env-file .env fastapi dev main.py

Check it worked

Bash
curl -s -w '\n' http://127.0.0.1:8000/health

The output is {"status":"ok"}.

Step 5 · Log in and call a protected route

Without a token, the protected route refuses you:

Bash
curl -s -w '\n%{http_code}\n' http://127.0.0.1:8000/users/me

The output is {"detail":"Not authenticated"} and then 401. The response also carries a WWW-Authenticate: Bearer header, which tells clients how to authenticate.

Log in. The login route takes a form, not JSON, because that is what the OAuth2 password flow specifies. To keep the password out of the process list, read it into a shell variable first and give it to curl through a config file on standard input. The -K - form reads curl options from stdin, and data-urlencode escapes the value for you:

Bash
read -rsp "Password: " PW; echo

Then define a small function, so you can log in again later without retyping the long line:

Bash
login() {
  printf 'data-urlencode = "password=%s"\n' "$PW" |
    curl -s -K - -d "username=$1" http://127.0.0.1:8000/token
}
TOKEN="$(login alice | jq -r .access_token)"
echo "${TOKEN:0:20}..."

The first characters of a JWT header are always eyJ, because that is the base64url form of {". A token starts eyJhbGciOiJIUzI1NiI. Now call the protected route with it:

Bash
curl -s -w '\n' -H "Authorization: Bearer $TOKEN" http://127.0.0.1:8000/users/me

The output is {"username":"alice"}.

Check it worked

Look inside the token. The payload is only base64url encoded, so you can read it. This is the reason to keep secrets out of it:

Bash
echo "$TOKEN" | cut -d. -f2 | tr '_-' '/+' | base64 -d 2>/dev/null | jq .

You see sub set to alice, an iat and an exp that is 900 seconds later. If base64 reports an input error, the padding is missing. The 2>/dev/null hides that message and jq still prints the data.

Step 6 · Try to break it

A login system is only as good as its refusals. Check the main ones by hand. A wrong password, an unknown user and a damaged token:

Bash
PW_GOOD="$PW"; PW="wrong password here"
login alice
echo
login nobody
echo
PW="$PW_GOOD"
curl -s -w '\n' -H "Authorization: Bearer ${TOKEN}x" http://127.0.0.1:8000/users/me

The first two print the identical {"detail":"Incorrect username or password"}: a caller cannot tell a wrong password from a missing user. The last prints {"detail":"Invalid or expired token"}, because the extra character breaks the signature.

Two attacks are awkward to do by hand, so test them in code: a token that has expired, and a token with alg: none (no signature at all). Write tests that call the app in-process. They sign their own tokens with the same secret, which is how you force an expiry in the past:

Bash
cd ~/jwt-api
mkdir -p tests
cat > tests/test_auth.py <<'PY'
import json
import os
from datetime import datetime, timedelta, timezone

import jwt
import pytest
from fastapi.testclient import TestClient
from pwdlib import PasswordHash

SECRET = os.environ["JWT_SECRET"]


@pytest.fixture()
def client(tmp_path, monkeypatch):
    users = tmp_path / "users.json"
    users.write_text(json.dumps({"alice": PasswordHash.recommended().hash("correct-horse-battery")}))
    monkeypatch.setenv("USERS_FILE", str(users))
    import importlib

    import main

    importlib.reload(main)
    return TestClient(main.app)


def token(client, **claims):
    base = {"sub": "alice", "exp": datetime.now(timezone.utc) + timedelta(minutes=5)}
    return jwt.encode({**base, **claims}, SECRET, algorithm="HS256")


def call(client, tok):
    return client.get("/users/me", headers={"Authorization": f"Bearer {tok}"})


def test_login_and_use_token(client):
    r = client.post("/token", data={"username": "alice", "password": "correct-horse-battery"})
    assert r.status_code == 200
    assert call(client, r.json()["access_token"]).json() == {"username": "alice"}


def test_wrong_password(client):
    r = client.post("/token", data={"username": "alice", "password": "nope-nope-nope"})
    assert r.status_code == 401


def test_expired_token_is_refused(client):
    past = datetime.now(timezone.utc) - timedelta(seconds=1)
    assert call(client, token(client, exp=past)).status_code == 401


def test_token_signed_with_another_secret_is_refused(client):
    forged = jwt.encode({"sub": "alice", "exp": datetime.now(timezone.utc) + timedelta(minutes=5)},
                        "x" * 32, algorithm="HS256")
    assert call(client, forged).status_code == 401


def test_unsigned_none_token_is_refused(client):
    unsigned = jwt.encode({"sub": "alice", "exp": datetime.now(timezone.utc) + timedelta(minutes=5)},
                          None, algorithm="none")
    assert call(client, unsigned).status_code == 401


def test_token_without_exp_is_refused(client):
    no_exp = jwt.encode({"sub": "alice"}, SECRET, algorithm="HS256")
    assert call(client, no_exp).status_code == 401


def test_token_for_deleted_user_is_refused(client):
    assert call(client, token(client, sub="mallory")).status_code == 401
PY

Run them. uv run --env-file supplies the secret:

Bash
uv run --env-file .env python -m pytest -q

The output ends with 7 passed.

Step 7 · Choose lifetimes and limits for production

Everything above is checked, but a few decisions are yours:

  • Short lifetime. A JWT cannot be revoked before it expires, because nothing on the server remembers it. That is why 15 minutes is a better default than a day. If a user must stay signed in longer, add a separate refresh token that you store on the server, so you can revoke it, and swap it for a new access token when the old one expires.
  • Where the client keeps the token. A mobile app can use the system keychain. In a browser, a token in localStorage can be read by any script that runs on your page, so many sites keep the token in an HttpOnly, Secure, SameSite cookie instead.
  • Brute force. Argon2 makes each guess slow, but it does not stop guessing. Limit the login route: rate limit an API with Nginx shows how.
  • HTTPS only. A bearer token in plain HTTP can be copied by anyone on the network path. Put the app behind a reverse proxy with a certificate, as in free HTTPS with Let's Encrypt and Nginx.
  • Rotating the secret. Changing JWT_SECRET signs everyone out at once, which is the right response to a leak.
  • Asymmetric keys. If other services must verify your tokens without being able to create them, sign with RS256 or ES256 (install pyjwt[crypto]) and share only the public key.

Troubleshooting

  • KeyError: 'JWT_SECRET' on start: the environment variable is not set. Start with uv run --env-file .env ....
  • FileNotFoundError: users.json: run create_user.py first, from the project folder.
  • 422 on /token: the body must be a form (-d, not --json) with username and password fields.
  • 401 Invalid or expired token right after login: the server was restarted with a different JWT_SECRET, or your computer's clock is wrong. Log in again.

Step 8 · Stop the server and clean up

Press Ctrl+C in the server terminal. The folder holds only what you made here, including the secret and the user file, so delete it:

Bash
cd ~
rm -rf ~/jwt-api

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.