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

1from fastapi import FastAPI, Depends
2from signalwire.core.security_config import SecurityConfig
3from signalwire.core.auth_handler import AuthHandler
4
5security = SecurityConfig()
6auth = AuthHandler(security)
7
8app = FastAPI()
9auth_dep = auth.get_fastapi_dependency()
10
11@app.get("/protected")
12async def protected_route(auth_result=Depends(auth_dep)):
13 return {"method": auth_result["method"]}
14
15# Optional auth -- don't reject unauthenticated requests
16optional_dep = auth.get_fastapi_dependency(optional=True)
17
18@app.get("/public")
19async def public_route(auth_result=Depends(optional_dep)):
20 if auth_result["authenticated"]:
21 return {"user": "authenticated"}
22 return {"user": "anonymous"}