FastAPI Security Introduction
When building APIs with FastAPI, implementing proper security measures is crucial to protect your application and your users' data. In this introduction, we'll explore the fundamental security concepts in FastAPI and how to implement them effectively.
Why API Security Matters
In today's interconnected world, APIs often handle sensitive information and provide access to critical functionality. Without proper security:
- Unauthorized users could access private data
- Malicious actors could manipulate your API
- User credentials might be exposed
- Your application could face compliance issues
FastAPI provides several built-in security utilities that help you implement industry-standard security practices with minimal effort.
Security Concepts in FastAPI
FastAPI's security features are built around a few key concepts:
- Authentication: Verifying the identity of users (who they are)
- Authorization: Determining what authenticated users can do
- Dependencies: FastAPI's mechanism for implementing reusable security logic
- OAuth2: Industry standard protocol for authorization
- JWT (JSON Web Tokens): A common method for securely transmitting information
Basic Authentication Example
Let's start with a simple username/password authentication example:
from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from typing import Annotated
import secrets
app = FastAPI()
security = HTTPBasic()
def get_current_username(
credentials: Annotated[HTTPBasicCredentials, Depends(security)]
):
current_username_bytes = credentials.username.encode("utf8")
correct_username_bytes = b"admin"
is_correct_username = secrets.compare_digest(
current_username_bytes, correct_username_bytes
)
current_password_bytes = credentials.password.encode("utf8")
correct_password_bytes = b"password123"
is_correct_password = secrets.compare_digest(
current_password_bytes, correct_password_bytes
)
if not (is_correct_username and is_correct_password):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
headers={"WWW-Authenticate": "Basic"},
)
return credentials.username
@app.get("/users/me")
def read_current_user(username: Annotated[str, Depends(get_current_username)]):
return {"username": username}
In this example:
- We use
HTTPBasic
from FastAPI's security modules - The
get_current_username
function verifies credentials - We use
secrets.compare_digest()
to prevent timing attacks - If authentication fails, we return a 401 Unauthorized error
When you run this application and navigate to /users/me
, your browser will prompt you for a username and password.
OAuth2 with Password Flow
For more complex applications, OAuth2 provides a robust framework for authentication:
from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from typing import Annotated
from pydantic import BaseModel
app = FastAPI()
# Simulated user database
fake_users_db = {
"johndoe": {
"username": "johndoe",
"full_name": "John Doe",
"email": "[email protected]",
"hashed_password": "fakehashed_secret",
"disabled": False,
}
}
# Data models
class User(BaseModel):
username: str
email: str | None = None
full_name: str | None = None
disabled: bool | None = None
class UserInDB(User):
hashed_password: str
# OAuth2 setup with token URL
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
# Utility functions
def get_user(db, username: str):
if username in db:
user_dict = db[username]
return UserInDB(**user_dict)
def fake_hash_password(password: str):
return f"fakehashed_{password}"
def fake_decode_token(token):
return get_user(fake_users_db, token)
async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]):
user = fake_decode_token(token)
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid authentication credentials",
headers={"WWW-Authenticate": "Bearer"},
)
return user
async def get_current_active_user(current_user: Annotated[User, Depends(get_current_user)]):
if current_user.disabled:
raise HTTPException(status_code=400, detail="Inactive user")
return current_user
@app.post("/token")
async def login(form_data: Annotated[OAuth2PasswordRequestForm, Depends()]):
user_dict = fake_users_db.get(form_data.username)
if not user_dict:
raise HTTPException(status_code=400, detail="Incorrect username or password")
user = UserInDB(**user_dict)
hashed_password = fake_hash_password(form_data.password)
if not hashed_password == user.hashed_password:
raise HTTPException(status_code=400, detail="Incorrect username or password")
return {"access_token": user.username, "token_type": "bearer"}
@app.get("/users/me")
async def read_users_me(current_user: Annotated[User, Depends(get_current_active_user)]):
return current_user
In this more advanced example:
- We define OAuth2 with password flow using
OAuth2PasswordBearer
- We create data models for users with Pydantic
- We implement a login endpoint that returns a token
- We use dependencies to extract and validate the user from the token
- We add an additional check for disabled users
To use this API:
- First make a POST request to
/token
with username and password - Use the returned token in the Authorization header for subsequent requests
JWT Authentication
For production applications, JWT (JSON Web Tokens) is often the preferred authentication method:
from datetime import datetime, timedelta
from typing import Annotated
from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from jose import JWTError, jwt
from passlib.context import CryptContext
from pydantic import BaseModel
# Secret key and algorithm configuration
# In production, store this securely and use a strong key
SECRET_KEY = "your-secret-key"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30
app = FastAPI()
# Password hashing utilities
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
# OAuth2 configuration
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
# Example user database
fake_users_db = {
"johndoe": {
"username": "johndoe",
"full_name": "John Doe",
"email": "[email protected]",
"hashed_password": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW",
"disabled": False,
}
}
# Data models
class Token(BaseModel):
access_token: str
token_type: str
class TokenData(BaseModel):
username: str | None = None
class User(BaseModel):
username: str
email: str | None = None
full_name: str | None = None
disabled: bool | None = None
class UserInDB(User):
hashed_password: str
# Helper functions
def verify_password(plain_password, hashed_password):
return pwd_context.verify(plain_password, hashed_password)
def get_password_hash(password):
return pwd_context.hash(password)
def get_user(db, username: str):
if username in db:
user_dict = db[username]
return UserInDB(**user_dict)
def authenticate_user(fake_db, username: str, password: str):
user = get_user(fake_db, username)
if not user:
return False
if not verify_password(password, user.hashed_password):
return False
return user
def create_access_token(data: dict, expires_delta: timedelta | None = None):
to_encode = data.copy()
if expires_delta:
expire = datetime.utcnow() + expires_delta
else:
expire = datetime.utcnow() + timedelta(minutes=15)
to_encode.update({"exp": expire})
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt
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
token_data = TokenData(username=username)
except JWTError:
raise credentials_exception
user = get_user(fake_users_db, username=token_data.username)
if user is None:
raise credentials_exception
return user
async def get_current_active_user(current_user: Annotated[User, Depends(get_current_user)]):
if current_user.disabled:
raise HTTPException(status_code=400, detail="Inactive user")
return current_user
@app.post("/token", response_model=Token)
async def login_for_access_token(form_data: Annotated[OAuth2PasswordRequestForm, Depends()]):
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_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
access_token = create_access_token(
data={"sub": user.username}, expires_delta=access_token_expires
)
return {"access_token": access_token, "token_type": "bearer"}
@app.get("/users/me", response_model=User)
async def read_users_me(current_user: Annotated[User, Depends(get_current_active_user)]):
return current_user
This implementation:
- Uses the
python-jose
library for JWT handling - Uses
passlib
for secure password hashing - Includes token expiration
- Properly validates tokens and extracts user information
- Uses Pydantic models for type safety
Security Best Practices
When implementing security in your FastAPI application:
- Never store plain text passwords - always use a proper hashing algorithm
- Use HTTPS in production to encrypt data in transit
- Implement rate limiting to prevent brute force attacks
- Keep secrets secure - use environment variables or secret management services
- Follow the principle of least privilege - only give users the access they need
- Validate all inputs - FastAPI helps with this but remain vigilant
- Keep dependencies updated to address security vulnerabilities
Real-World Security Implementation
In real-world applications, you would typically:
- Use a database to store user information
- Implement role-based access control (RBAC)
- Add refresh token functionality
- Implement additional security headers
- Add CORS protection
Here's how you might set up a protected endpoint with role-based access:
from fastapi import Depends, FastAPI, HTTPException, Security, status
from fastapi.security import OAuth2PasswordBearer, SecurityScopes
from typing import Annotated, List
from pydantic import BaseModel, ValidationError
app = FastAPI()
# Simplified for example purposes
oauth2_scheme = OAuth2PasswordBearer(
tokenUrl="token",
scopes={"admin": "Admin access", "user": "Regular user access"}
)
class User(BaseModel):
username: str
email: str
scopes: List[str] = []
disabled: bool = False
# Mock user database
users_db = {
"john": User(
username="john",
email="[email protected]",
scopes=["user"]
),
"jane": User(
username="jane",
email="[email protected]",
scopes=["user", "admin"]
)
}
async def get_current_user(
security_scopes: SecurityScopes,
token: Annotated[str, Depends(oauth2_scheme)]
):
if security_scopes.scopes:
authenticate_value = f'Bearer scope="{security_scopes.scope_str}"'
else:
authenticate_value = "Bearer"
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": authenticate_value},
)
# In a real app, you'd verify the JWT here
# This is simplified for the example
if token not in users_db:
raise credentials_exception
user = users_db[token]
# Check that the user has the required scopes
for scope in security_scopes.scopes:
if scope not in user.scopes:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Not enough permissions",
headers={"WWW-Authenticate": authenticate_value},
)
return user
@app.get("/users/me")
async def read_users_me(current_user: Annotated[User, Depends(get_current_user)]):
return current_user
@app.get("/admin", dependencies=[Depends(Security(get_current_user, scopes=["admin"]))])
async def read_admin():
return {"message": "Admin access granted"}
In this example, only users with the "admin" scope can access the /admin
endpoint, while all authenticated users can access /users/me
.
Summary
In this introduction to FastAPI security, we've covered:
- Basic authentication with username and password
- OAuth2 implementation with password flow
- JWT authentication for production use
- Security best practices
- Role-based access control
These foundations will help you build secure FastAPI applications. In the upcoming sections, we'll dive deeper into specific security techniques and more advanced patterns.
Additional Resources
Exercises
- Implement a simple FastAPI application with basic authentication
- Extend the JWT example to include refresh tokens
- Create an API with different endpoints that require different roles
- Implement rate limiting on login endpoints to prevent brute force attacks
- Add proper password validation (minimum length, special characters, etc.)
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)