Protect Endpoints With Auth Dependency
Learn how the auth dependency can be used to protect authenticated APIs.
Previously, during the Wristband SDK setup, we created an auth dependency named require_session_auth
. This section explains how to use it to ensure that protected endpoints are accessible only to authenticated users.
Using the Auth Dependency to Protect Endpoints
To protect an endpoint from unauthenticated access, simply inject the require_session_auth
dependency into the endpoint, as shown in the following example:
# 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 to verify that
# incoming requests have a valid session.
@router.get("/protected-api", dependencies=[Depends(require_session_auth)])
async def protected_api() -> Response:
return { "message": "This is a protected endpoint" }
Now, if somebody tries to call this API without a valid session, a 401 Unauthorized response will be returned.
Updated about 11 hours ago
What’s Next
Next, let's look at how to synchronize session information with the frontend.