get_fastapi_dependency

View as MarkdownOpen in Claude

Get a FastAPI dependency function that can be used with Depends() to protect routes. The dependency tries each enabled auth method in order: Bearer token and Basic Auth.

Parameters

optional
boolDefaults to false

When True, unauthenticated requests pass through with {"authenticated": False} instead of raising a 401 error.

Returns

Callable — An async function suitable for use as a FastAPI dependency. Returns a dict with authenticated (bool) and method (str or None) keys.

Example

from fastapi import FastAPI, Depends
from signalwire.core.security_config import SecurityConfig
from signalwire.core.auth_handler import AuthHandler
security = SecurityConfig()
auth = AuthHandler(security)
app = FastAPI()
auth_dep = auth.get_fastapi_dependency()
@app.get("/protected")
async def protected_route(auth_result=Depends(auth_dep)):
return {"method": auth_result["method"]}
# Optional auth -- don't reject unauthenticated requests
optional_dep = auth.get_fastapi_dependency(optional=True)
@app.get("/public")
async def public_route(auth_result=Depends(optional_dep)):
if auth_result["authenticated"]:
return {"user": "authenticated"}
return {"user": "anonymous"}