Authentication and Security
10 min read
Course: FastAPI
Topic: Authentication and Security
Hey there, future security wizard! π§ββοΈ Welcome to a super important part of building any real-world application: Authentication and Security. It's time to put a digital lock on our doors and make sure only the right people get in.
Let's be honest, building an API without security is like leaving your diary open in a crowded coffee shop. You just don't do it. In this guide, we'll go from leaving our doors wide open to building a secure fortress, but you know, a fun fortress with a friendly guard.
1. Security Fundamentals and FastAPI Security Tools π‘οΈ
What's the Big Deal with Security?
The Problem: You've built a fantastic API that does amazing things. But right now, anyone can access it. Anyone can see user data, anyone can create or delete things. It's a free-for-all! This is bad because you want to control who can use your API and what they can do. For example, you wouldn't want a random stranger to be able to see your private messages or delete your account, right?
The Solution: We need a system to verify the identity of a user (Authentication) and determine what they are allowed to do (Authorization). Think of it like a bouncer at a club. First, they check your ID to make sure you are who you say you are (Authentication). Then, they check if you have a VIP pass to access the special lounge (Authorization).
FastAPI is built on top of Starlette and Pydantic, and it provides a simple but powerful set of tools to implement security, all based on industry standards.
FastAPI's Security Arsenal
FastAPI gives us a bunch of tools in a module called fastapi.security. These aren't new security inventions but are implementations of well-established standards. The main ones we'll focus on are for OAuth2, the industry-standard protocol for authorization.
Imagine you're building a new apartment complex. Instead of inventing your own new type of lock and key, which would probably be easy to pick, you'd use a trusted, industry-standard lock that has been tested and proven to be secure. That's what FastAPI does; it gives you the tools to easily install these trusted "locks" on your API endpoints.
We'll primarily be using:
OAuth2PasswordBearer: A class that helps us handle the "bearer" token flow. A "bearer token" is just a fancy way of saying, "whoever bears (carries) this token has access."OAuth2PasswordRequestForm: A dependency that helps us handle the form data (usernameandpassword) that a user will send to log in.
Don't worry, we'll see exactly how to use these in the next sections. For now, just know that FastAPI isn't reinventing the wheel; it's giving you a high-quality, pre-made wheel to use.
2. Implementing OAuth2 with Password Flow π
The Problem: We need a way for our users to prove who they are. The most common way to do this is with a username and password. But we can't just send the username and password with every single request. That's inefficient and insecure.
The Solution: The "Password Flow" of OAuth2. It's a fancy name for a simple process:
- The user sends their username and password to a specific endpoint (e.g.,
/loginor/token). - The server checks if the username and password are correct.
- If they are correct, the server generates a unique, temporary "token" and sends it back to the user.
- For all future requests to protected endpoints, the user sends this token in the
Authorizationheader. - The server then just needs to validate this token for every request.
This is like getting a wristband at a music festival. You show your ticket (username and password) once at the entrance. They give you a wristband (the token). Now, to get into different stages, you just show your wristband. You don't have to pull out your main ticket every single time.
Getting Set Up
First, we need to install the necessary libraries. We need python-multipart to handle the form data and passlib with bcrypt to handle password hashing (we'll get to that!).
pip install "fastapi[all]" python-multipart "passlib[bcrypt]"Creating the Token Endpoint
Let's create the endpoint where our users can exchange their username and password for a token.
from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordRequestForm
from typing import Annotated
app = FastAPI()
@app.post("/token")
async def login(form_data: Annotated[OAuth2PasswordRequestForm, Depends()]):
# This is a dummy user check for now.
# In a real app, you would look up the user in your database
# and check if the hashed password matches.
if not form_data.username == "johndoe" or not form_data.password == "secret":
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
headers={"WWW-Authenticate": "Bearer"},
)
# For now, we'll just return a dummy token.
# We will generate a real JWT in the next section.
return {"access_token": "some_dummy_token", "token_type": "bearer"}
What's happening here?
- We created a
/tokenendpoint that only accepts POST requests. - We use
Annotated[OAuth2PasswordRequestForm, Depends()]. This is a dependency that tells FastAPI to expect form data withusernameandpasswordfields. - We are doing a very basic check for the user. Fun Fact: Hardcoding credentials like this is a massive security no-no in the real world! It's like writing your bank PIN on the back of your credit card. We're just doing it here to learn the flow.
- If the credentials are bad, we raise a 401 "Unauthorized" error.
- If they are good, we send back a dictionary with an
access_token.
3. Generating and Validating JWT (JSON Web Tokens) π
The Problem: Our last step returned a "dummy token". That's not very secure or useful. We need a token that is secure, contains information (like who the user is), and has an expiration date.
The Solution: JSON Web Tokens (JWTs). A JWT is just a long string of text, but it's a special, standardized string. It's composed of three parts separated by dots: header.payload.signature.
- Header: Contains metadata, like the type of token (JWT) and the signing algorithm used.
- Payload: Contains the "claims" or the data we want to store. A common claim is
sub(subject), which we can use to store the username or user ID. We can also add anexp(expiration time) claim. - Signature: This is the magic part. The header and payload are taken, a secret key is added, and everything is signed with a cryptographic algorithm. This signature ensures that the token hasn't been tampered with.
Imagine a sealed letter. The header is the envelope saying "This is a letter", the payload is the actual letter content, and the signature is the wax seal. If the seal is broken, you know someone has messed with the letter.
Installation
We need a library to handle the creation and validation of JWTs. The FastAPI documentation recommends python-jose.
pip install "python-jose[cryptography]"Creating a JWT
Let's update our /token endpoint to create a real JWT.
from datetime import datetime, timedelta, timezone
from jose import JWTError, jwt
from passlib.context import CryptContext
# --- Configuration ---
SECRET_KEY = "your-super-secret-key" # Keep this secret!
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30
# --- Hashing Passwords (A quick detour!) ---
# We should never store passwords in plain text.
# We store a "hash" of the password.
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
# ... inside your /token endpoint ...
@app.post("/token")
async def login_for_access_token(form_data: Annotated[OAuth2PasswordRequestForm, Depends()]):
# In a real app, you'd fetch the user from the DB and verify the password
# user = get_user_from_db(form_data.username)
# if not user or not pwd_context.verify(form_data.password, user.hashed_password):
# raise HTTPException(...)
# Dummy check for now
if not form_data.username == "johndoe" or not form_data.password == "secret":
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
)
access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
expire = datetime.now(timezone.utc) + access_token_expires
to_encode = {"sub": form_data.username, "exp": expire}
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
return {"access_token": encoded_jwt, "token_type": "bearer"}What did we do?
- SECRET_KEY: This is a secret string that only our server knows. If someone else gets this, they can forge tokens. Keep it safe!
- Payload Data: We created a dictionary
to_encodewith the username as thesub(subject) and anexp(expiration time). Setting an expiration time is crucial! You don't want tokens that live forever. - jwt.encode(): We used the
joselibrary to take our payload, our secret key, and the algorithm, and it magically produced a signed JWT for us.
4. Securing Endpoints: Building a get_current_user Dependency π
The Problem: Okay, so the user has a token. Now what? How do we protect our other endpoints and make sure only users with a valid token can access them? And how do we know which user is making the request?
The Solution: A dependency! We can create a function that does all the hard work of checking for the token, validating it, decoding it, and fetching the user. We can then "depend" on this function in any endpoint we want to protect.
This is like having a dedicated security guard for the VIP lounge. Before anyone enters, the guard is responsible for checking their wristband, making sure it's not fake, and confirming it's for the right event.
Creating the Dependency
Let's build our get_current_user dependency.
from fastapi.security import OAuth2PasswordBearer
# This tells FastAPI where the client can go to get the token.
# It doesn't create the endpoint, it just provides the URL for documentation purposes.
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]):
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: str = payload.get("sub")
if username is None:
raise credentials_exception
# In a real app, you might fetch the user object from the database here
# user = get_user_from_db(username=username)
except JWTError:
raise credentials_exception
# For now, we'll just return the username from the token
return {"username": username}
@app.get("/users/me")
async def read_users_me(current_user: Annotated[dict, Depends(get_current_user)]):
return current_userLet's break down this powerful piece of code:
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token"): We create an instance ofOAuth2PasswordBearer. This is an object that knows how to find the token in the request'sAuthorizationheader. We give it the URL of our token endpoint.get_current_user(token: Annotated[str, Depends(oauth2_scheme)]):- This is our dependency function.
Depends(oauth2_scheme)is magic. It tells FastAPI: "Before you run the code in this function, look for anAuthorizationheader in the request, check if it has a Bearer token, and pass that token string to thetokenparameter." If it doesn't find a token, it will stop and return an error automatically!
jwt.decode(): We try to decode the token using ourSECRET_KEY. If the token is expired, has been tampered with, or is just plain wrong,python-josewill raise aJWTError.- Error Handling: We wrap the decoding in a
try...exceptblock. If anything goes wrong, we raise our consistentcredentials_exception. - Payload Extraction: If the token is valid, we extract the username from the
subclaim. - Using the Dependency: In our
/users/meendpoint, we addcurrent_user: Annotated[dict, Depends(get_current_user)]to the parameters. Now, before a request can even reach our endpoint's code, FastAPI will runget_current_user. The return value of that function (our user dictionary) will be passed into thecurrent_userparameter.
And that's it! π You've now built the core of a secure authentication system. Any endpoint where you add Depends(get_current_user) is now protected. If a user tries to access it without a valid token, they'll be denied. If they provide a valid token, you'll know exactly who they are.
Extra Reading & References
- FastAPI Security Docs: The official source of truth. Always a great place to start. https://fastapi.tiangolo.com/tutorial/security/
- OAuth2 Password Flow: A deeper dive into the specific flow we used. https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/
- JWT Introduction: A great resource for understanding JSON Web Tokens. https://jwt.io/introduction
- Passlib Docs: For when you need to get serious about password hashing. https://passlib.readthedocs.io/en/stable/index.html
Challenge
Challenge: Implement a Complete JWT Authentication Flow in FastAPI
You are tasked with building a secure authentication layer for a FastAPI application from scratch. Your implementation must use the OAuth2 Password Flow with JSON Web Tokens (JWT).
Requirements:
Configuration: Define the following constants at the top of your file:
SECRET_KEY: A secure, secret string of your choice.ALGORITHM: Use"HS256".ACCESS_TOKEN_EXPIRE_MINUTES: Set to30.
OAuth2 Scheme: Instantiate
OAuth2PasswordBearerwith thetokenUrlpointing to the/tokenendpoint.Token Creation Logic: Implement a function
create_access_tokenthat accepts a data dictionary and an optionalexpires_delta. This function should:- Create a copy of the input data.
- Calculate the token expiration time (
expclaim) based on the current UTC time andexpires_delta. - Update the data copy with the
expclaim. - Encode the data into a JWT string using the defined
SECRET_KEYandALGORITHM. - Return the encoded JWT string.
Token Endpoint (
/token): Create a POST endpoint at/tokenthat:- Accepts
usernameandpasswordfrom anOAuth2PasswordRequestForm. - Authenticates the user. For this challenge, use a hardcoded user with
username="testuser"andpassword="testpassword". Do not implement password hashing for this exercise. - If authentication fails, raise an
HTTPExceptionwithstatus_code401 and the detail"Incorrect username or password". - If authentication is successful, use your
create_access_tokenfunction to generate a new token with an appropriate expiration delta. - Return the token in a JSON response with the format:
{"access_token": "your_token_here", "token_type": "bearer"}.
- Accepts
User Dependency (
get_current_user): Create an asynchronous dependency functionget_current_userthat:- Depends on the
OAuth2PasswordBearerinstance to extract the token from the request's Authorization header. - Defines a
credentials_exception(HTTPException, status code 401, detail"Could not validate credentials", and headers{"WWW-Authenticate": "Bearer"}). - Attempts to decode the JWT. If a
JWTErroroccurs, raise thecredentials_exception. - Extracts the username from the
subclaim in the decoded payload. If thesubclaim is missing, raise thecredentials_exception. - Returns the username.
- Depends on the
Protected Endpoint (
/users/me): Create a GET endpoint at/users/methat:- Is protected by and depends on your
get_current_userfunction. - Returns a JSON object with the authenticated user's username, like
{"username": "testuser"}.
- Is protected by and depends on your
Expected result
Your final code should be a single, complete FastAPI application script that correctly implements all the requirements. When finished, your script must:
- Have the
SECRET_KEY,ALGORITHM, andACCESS_TOKEN_EXPIRE_MINUTESconstants defined with the specified values. - Correctly initialize
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token"). - The
create_access_tokenfunction must properly encode a JWT payload containingsubandexpclaims usingjose.jwt.encode. - The
get_current_userfunction must be anasyncfunction that correctly decodes a JWT, validates its claims, handlesJWTErrorand missingsubclaims by raising a 401HTTPExceptionwith the specified detail andWWW-Authenticateheader, and returns the username upon success. - The
/tokenendpoint must acceptOAuth2PasswordRequestFormdata, validate credentials against the hardcoded'testuser'and'testpassword', callcreate_access_tokenupon success, and return a JSON object withaccess_tokenandtoken_typekeys. It must raise a 401HTTPExceptionon authentication failure. - The
/users/meendpoint must be decorated to depend onget_current_userand return a JSON object containing the username of the currently authenticated user.