Protect Endpoints With The Auth Dependency

Inject an auth dependency to ensure only authenticated users can access sensitive APIs.

Now that we've tested that your login flow is working properly thus far, let's add our FastAPI auth dependency to verify that only users with valid sessions can access protected backend APIs.


Inject Auth Dependency On Your Application's Protected Endpoints

Add the auth dependency to any endpoint that requires an authenticated user session. Below is an example of how to secure your endpoints with this dependency:

# src/routes/protected_routes.py
from fastapi import APIRouter, Depends, Response, status
from auth.wristband import require_session_auth  # <-- Import your auth dependency

router = APIRouter()

# Use the require_session_auth dependency in your dependencies list
@router.get("/protected-api", dependencies=[Depends(require_session_auth)])
async def protected_api() -> Response:
    return { "message": "This is a protected endpoint" }

📘

Does The Auth Dependency Need to be Applied to The Auth Endpoints?

The Login, Callback, and Logout Endpoints are meant to be accessed by unauthenticated users, so you don't need to inject the auth dependency on those.



What’s Next

Now that your server endpoints are protected, let's handle sessions and auth on the frontend.