How to Protect Routes in FastAPI: Secure Your API Endpoints
To protect routes in
FastAPI, use dependencies that check authentication or authorization before allowing access. Commonly, you create a Depends function that verifies user credentials or tokens and include it in your route definitions to restrict access.Syntax
In FastAPI, route protection is done by adding a dependency that performs security checks. This dependency is passed to the route using Depends. The dependency function can verify tokens, user credentials, or permissions.
Depends(security_function): Injects the security check.security_function: A function that raises an error if the user is unauthorized.@app.get("/protected"): The route you want to protect.
python
from fastapi import FastAPI, Depends, HTTPException, status from fastapi.security import OAuth2PasswordBearer app = FastAPI() oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") def get_current_user(token: str = Depends(oauth2_scheme)): if token != "secrettoken": raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid authentication credentials", headers={"WWW-Authenticate": "Bearer"} ) return "user" @app.get("/protected") async def protected_route(current_user: str = Depends(get_current_user)): return {"message": f"Hello, {current_user}! This is a protected route."}
Example
This example shows how to protect a route using OAuth2 password bearer token. The get_current_user function checks if the token is valid and raises an error if not. The protected route returns a greeting only if the user is authenticated.
python
from fastapi import FastAPI, Depends, HTTPException, status from fastapi.security import OAuth2PasswordBearer app = FastAPI() oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") def get_current_user(token: str = Depends(oauth2_scheme)): if token != "secrettoken": raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid authentication credentials", headers={"WWW-Authenticate": "Bearer"} ) return "user" @app.get("/protected") async def protected_route(current_user: str = Depends(get_current_user)): return {"message": f"Hello, {current_user}! This is a protected route."}
Output
HTTP 401 Unauthorized if token is invalid; HTTP 200 with JSON {"message": "Hello, user! This is a protected route."} if token is 'secrettoken'
Common Pitfalls
- Not raising
HTTPExceptionon failed authentication causes routes to be accessible without protection. - Forgetting to include the dependency in the route means no protection is applied.
- Using plain strings for tokens without secure verification is unsafe.
- Not using HTTPS in production exposes tokens to interception.
python
from fastapi import FastAPI, Depends app = FastAPI() def insecure_auth(): # This does not raise an error, so route is not protected return "user" @app.get("/unprotected") async def unprotected_route(user: str = Depends(insecure_auth)): return {"message": f"Hello, {user}! This route is not really protected."} # Correct way from fastapi import HTTPException, status from fastapi.security import OAuth2PasswordBearer from fastapi import Depends oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") def secure_auth(token: str = Depends(oauth2_scheme)): if token != "secrettoken": raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Unauthorized", headers={"WWW-Authenticate": "Bearer"}) return "user" @app.get("/protected") async def protected_route(user: str = Depends(secure_auth)): return {"message": f"Hello, {user}! This route is protected."}
Quick Reference
Summary tips for protecting routes in FastAPI:
- Use
Dependswith a security function to enforce authentication. - Raise
HTTPExceptionwith status 401 for unauthorized access. - Use
fastapi.securityutilities likeOAuth2PasswordBearerfor token handling. - Always verify tokens or credentials securely.
- Test routes with and without valid tokens to confirm protection.
Key Takeaways
Protect FastAPI routes by adding a dependency that verifies user authentication.
Use fastapi.security utilities like OAuth2PasswordBearer for token-based security.
Always raise HTTPException with 401 status to block unauthorized access.
Include the security dependency in every route you want to protect.
Test your protected routes with valid and invalid tokens to ensure security.