0
0
FastapiHow-ToBeginner · 4 min read

How to Use Dependency for Authentication in FastAPI

In FastAPI, use Depends to create a dependency function that handles authentication logic, such as verifying tokens or credentials. Then, include this dependency in your route functions to automatically enforce authentication before processing requests.
📐

Syntax

Use Depends from FastAPI to declare a dependency function that performs authentication. This function can check headers, tokens, or credentials and return the authenticated user or raise an error if authentication fails.

In your route, add a parameter with Depends(auth_function) to require authentication before the route runs.

python
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer

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",
        )
    return {"username": "user1"}

# Usage in route
from fastapi import FastAPI
app = FastAPI()

@app.get("/users/me")
async def read_users_me(current_user: dict = Depends(get_current_user)):
    return current_user
💻

Example

This example shows a simple token-based authentication using dependency injection. The get_current_user function checks the token and returns user info if valid. The route /users/me requires this dependency, so it only runs if authentication succeeds.

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",
        )
    return {"username": "user1"}

@app.get("/users/me")
async def read_users_me(current_user: dict = Depends(get_current_user)):
    return {"message": "Welcome", "user": current_user}

# To test, send a request with header Authorization: Bearer secrettoken
Output
{"message": "Welcome", "user": {"username": "user1"}}
⚠️

Common Pitfalls

  • Not using Depends in the route parameter, so authentication is not enforced.
  • Raising generic exceptions instead of HTTPException with proper status codes.
  • Forgetting to include the security scheme like OAuth2PasswordBearer to extract tokens.
  • Hardcoding tokens or credentials without secure storage or hashing.
python
from fastapi import FastAPI

app = FastAPI()

# Wrong: missing Depends, so no authentication check
@app.get("/open")
def open_route():
    return {"message": "No auth required"}

# Right: use Depends to enforce auth
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer

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 token")
    return {"username": "user1"}

@app.get("/secure")
async def secure_route(current_user: dict = Depends(get_current_user)):
    return {"message": "Secure data", "user": current_user}
📊

Quick Reference

Dependency Injection for Authentication in FastAPI:

  • Define a function that checks authentication and returns user info or raises HTTPException.
  • Use Depends in route parameters to call this function automatically.
  • Use FastAPI security utilities like OAuth2PasswordBearer to extract tokens.
  • Raise HTTPException with status 401 for unauthorized access.

Key Takeaways

Use FastAPI's Depends to inject authentication logic into routes.
Create a dependency function that validates tokens or credentials and returns user info.
Raise HTTPException with status 401 to reject unauthorized requests.
Include security schemes like OAuth2PasswordBearer to extract tokens from requests.
Always add the dependency parameter in routes to enforce authentication.