Learn FastAPI Β· 8/14

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 (username and password) 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:

  1. The user sends their username and password to a specific endpoint (e.g., /login or /token).
  2. The server checks if the username and password are correct.
  3. If they are correct, the server generates a unique, temporary "token" and sends it back to the user.
  4. For all future requests to protected endpoints, the user sends this token in the Authorization header.
  5. 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!).

bash
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.

python
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 /token endpoint that only accepts POST requests.
  • We use Annotated[OAuth2PasswordRequestForm, Depends()]. This is a dependency that tells FastAPI to expect form data with username and password fields.
  • 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 an exp (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.

bash
pip install "python-jose[cryptography]"

Creating a JWT

Let's update our /token endpoint to create a real JWT.

python
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?

  1. SECRET_KEY: This is a secret string that only our server knows. If someone else gets this, they can forge tokens. Keep it safe!
  2. Payload Data: We created a dictionary to_encode with the username as the sub (subject) and an exp (expiration time). Setting an expiration time is crucial! You don't want tokens that live forever.
  3. jwt.encode(): We used the jose library 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.

python
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_user

Let's break down this powerful piece of code:

  1. oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token"): We create an instance of OAuth2PasswordBearer. This is an object that knows how to find the token in the request's Authorization header. We give it the URL of our token endpoint.
  2. 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 an Authorization header in the request, check if it has a Bearer token, and pass that token string to the token parameter." If it doesn't find a token, it will stop and return an error automatically!
  3. jwt.decode(): We try to decode the token using our SECRET_KEY. If the token is expired, has been tampered with, or is just plain wrong, python-jose will raise a JWTError.
  4. Error Handling: We wrap the decoding in a try...except block. If anything goes wrong, we raise our consistent credentials_exception.
  5. Payload Extraction: If the token is valid, we extract the username from the sub claim.
  6. Using the Dependency: In our /users/me endpoint, we add current_user: Annotated[dict, Depends(get_current_user)] to the parameters. Now, before a request can even reach our endpoint's code, FastAPI will run get_current_user. The return value of that function (our user dictionary) will be passed into the current_user parameter.

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

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:

  1. 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 to 30.
  2. OAuth2 Scheme: Instantiate OAuth2PasswordBearer with the tokenUrl pointing to the /token endpoint.

  3. Token Creation Logic: Implement a function create_access_token that accepts a data dictionary and an optional expires_delta. This function should:

    • Create a copy of the input data.
    • Calculate the token expiration time (exp claim) based on the current UTC time and expires_delta.
    • Update the data copy with the exp claim.
    • Encode the data into a JWT string using the defined SECRET_KEY and ALGORITHM.
    • Return the encoded JWT string.
  4. Token Endpoint (/token): Create a POST endpoint at /token that:

    • Accepts username and password from an OAuth2PasswordRequestForm.
    • Authenticates the user. For this challenge, use a hardcoded user with username="testuser" and password="testpassword". Do not implement password hashing for this exercise.
    • If authentication fails, raise an HTTPException with status_code 401 and the detail "Incorrect username or password".
    • If authentication is successful, use your create_access_token function 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"}.
  5. User Dependency (get_current_user): Create an asynchronous dependency function get_current_user that:

    • Depends on the OAuth2PasswordBearer instance 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 JWTError occurs, raise the credentials_exception.
    • Extracts the username from the sub claim in the decoded payload. If the sub claim is missing, raise the credentials_exception.
    • Returns the username.
  6. Protected Endpoint (/users/me): Create a GET endpoint at /users/me that:

    • Is protected by and depends on your get_current_user function.
    • Returns a JSON object with the authenticated user's username, like {"username": "testuser"}.

Expected result

Your final code should be a single, complete FastAPI application script that correctly implements all the requirements. When finished, your script must:

  1. Have the SECRET_KEY, ALGORITHM, and ACCESS_TOKEN_EXPIRE_MINUTES constants defined with the specified values.
  2. Correctly initialize oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token").
  3. The create_access_token function must properly encode a JWT payload containing sub and exp claims using jose.jwt.encode.
  4. The get_current_user function must be an async function that correctly decodes a JWT, validates its claims, handles JWTError and missing sub claims by raising a 401 HTTPException with the specified detail and WWW-Authenticate header, and returns the username upon success.
  5. The /token endpoint must accept OAuth2PasswordRequestForm data, validate credentials against the hardcoded 'testuser' and 'testpassword', call create_access_token upon success, and return a JSON object with access_token and token_type keys. It must raise a 401 HTTPException on authentication failure.
  6. The /users/me endpoint must be decorated to depend on get_current_user and return a JSON object containing the username of the currently authenticated user.
python

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.