Lesson 37 of 45 ยท FastAPI Basics
Security - OAuth2 with JWT Tokens
Implement secure authentication using JWT tokens with password hashing and OAuth2 Bearer authentication.
Open this lesson in the editor โWhat you'll learn
- Implement JWT token generation and verification
- Use password hashing for secure storage
- Create secure OAuth2 authentication flow
- Handle token expiration and validation
OAuth2 with Password (and hashing), Bearer with JWT tokens
๐ฏ What You'll Learn
- Store passwords as bcrypt hashes and check a login against the hash
- Issue a signed JWT that expires
- Accept only tokens your server signed, and refuse everything else with 401
- Keep the password hash out of every response
๐ Theory
The previous lesson built the whole OAuth2 password flow, but both of its security steps were fake: the "hash" was the password with fakehashed in front, and the token was simply the username. Anyone could send Authorization: Bearer johndoe and be John Doe.
This lesson replaces both with the real thing. The rest of the flow stays the same, so the starter already contains it: the User and UserInDB models, get_user, oauth2_scheme and get_current_active_user. Your part is the nine numbered steps marked in the starter, in order. Each section below names the step it covers.
About JWT
JWT means "JSON Web Tokens". It's a standard to codify a JSON object in a long, dense string without spaces. It looks like this:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
It is not encrypted: anyone can read what is inside. But it is signed with your SECRET_KEY, so when a token comes back you can check that you issued it and that nobody changed it. Change one character of the contents and the signature no longer matches.
That is what makes expiry safe. You put an expiry time in the token, and when the user comes back with it you know whether it is still valid. Nobody can extend it by editing the token, because the edited token would fail the signature check.
About password hashing
A hash turns a password into a string that cannot be turned back into the password. To check a login, you hash what the user typed and compare. If your database is ever stolen, the thief gets hashes, not passwords.
This lesson uses passlib with the bcrypt algorithm. fake_users_db stores johndoe's password ("secret") only as its bcrypt hash.
FastAPI's own documentation now uses pwdlib with Argon2 for this step. The idea is identical: hash on sign-up, verify on login. passlib with bcrypt is what this runtime has.
๐ง Key Concepts
The Token model (step 1)
What POST /token returns. OAuth2 says the response must have these two fields:
class Token(BaseModel):
access_token: str
token_type: str
Hashing and verifying (steps 2 and 3)
from passlib.context import CryptContext
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
hashed = pwd_context.hash("secret") # how the stored hash was made
pwd_context.verify("secret", hashed) # True
pwd_context.verify("wrong", hashed) # False
Spell the scheme exactly "bcrypt": any other name fails as soon as the app loads.
Authenticating a user (step 4)
Look the user up, then check the password. Return False in both failure cases, so the caller cannot tell "no such user" from "wrong password":
def authenticate_user(db, username: str, password: str):
user = get_user(db, username)
if not user:
return False
if not verify_password(password, user.hashed_password):
return False
return user
Creating a token (step 5)
The token carries whatever data you pass in, plus an exp (expiry) claim. Use a timezone-aware time: datetime.utcnow() is deprecated.
def create_access_token(data: dict, expires_delta: timedelta):
to_encode = data.copy()
to_encode["exp"] = datetime.now(timezone.utc) + expires_delta
return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
By convention the user goes in the sub ("subject") claim: create_access_token({"sub": "johndoe"}, ...).
Checking a token (step 6)
jwt.decode does the security work. It raises InvalidTokenError if the signature does not match, if the token is malformed, or if exp has passed (ExpiredSignatureError is a subclass). Every one of those must end in 401:
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
except InvalidTokenError:
raise credentials_exception
username = payload.get("sub")
if username is None:
raise credentials_exception
Then look the user up with get_user and raise credentials_exception if nobody has that name. Always pass algorithms=[...] as a list. It stops a token from choosing its own algorithm.
The login endpoint (step 7)
OAuth2PasswordRequestForm reads the username and password form fields that OAuth2 clients send. Same as the previous lesson, but now the password is checked properly and a real token comes back:
@app.post("/token")
async def login_for_access_token(
form_data: Annotated[OAuth2PasswordRequestForm, Depends()],
) -> Token:
user = authenticate_user(fake_users_db, 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")
Never send the hash back (step 8)
get_current_user returns a UserInDB, the model that carries hashed_password. Return it as it is and the hash goes to the client:
{"username": "johndoe", "email": "johndoe@example.com", "full_name": "John Doe",
"disabled": false, "hashed_password": "$2b$12$EixZaYVK1fsbw1Zf..."}
Declaring response_model=User makes FastAPI send only User's fields, whatever the function returns:
@app.get("/users/me/", response_model=User)
async def read_users_me(current_user: Annotated[User, Depends(get_current_active_user)]):
return current_user
A second protected endpoint (step 9)
Any endpoint that depends on get_current_active_user is protected the same way. /users/me/items/ returns the user's items: [{"item_id": "Foo", "owner": "johndoe"}] for johndoe.
๐งช What Run checks
Run logs in through your own POST /token first, then uses the token it gets back. It checks six things:
| Request | Expected |
|---|---|
POST /token, johndoe / secret | 200, a token, "token_type": "bearer" |
GET /users/me/ with that token | 200, johndoe's profile, no hashed_password |
GET /users/me/items/ with that token | 200, [{"item_id": "Foo", "owner": "johndoe"}] |
POST /token, johndoe / wrong | 401 |
GET /users/me/ with no token | 401 |
GET /users/me/ with a token signed by a different key | 401 |
The last three are the point of the lesson: an app that answers every request is not secure, however correct its answers look. If POST /token fails, fix it first, because the protected endpoints are called with the token it returns.
Trying it by hand
- Open the Endpoints tab and press Test next to
POST /token. - Copy the
access_tokenvalue from the response. - Press Auth (top right of the panel), paste the token, and test
GET /users/me/. It now sendsAuthorization: Bearer <token>. - Clear the token and test
GET /users/me/again: you should get 401.
Paste the token into jwt.io to see that its contents are readable (sub and exp), and that the signature only verifies with your SECRET_KEY.
๐ก Best Practices
- Keep
SECRET_KEYout of the code. Anyone who has it can sign tokens your server will accept. Load it from the environment, and generate it withopenssl rand -hex 32. - Short expiry. 15 to 30 minutes is typical; use refresh tokens if users need longer sessions.
- Same answer for every failed login. "Incorrect username or password", never which of the two was wrong.
- HTTPS only. A bearer token works for whoever holds it.
- Rate-limit
/tokenso passwords cannot be guessed at speed.
๐ Additional Resources
Hint
Work through the TODOs in order: each one uses the ones before it. If Run says POST /token failed, look at TODOs 1-5 and 7 first: every protected endpoint needs the token it returns. Run also checks the refusals: no token, a forged token and a wrong password must each get 401.
Now write it
The editor runs a real FastAPI server and grades your code against this lesson's own endpoints.
Start Security - OAuth2 with JWT Tokens