-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path03_fastapi_server.py
More file actions
59 lines (41 loc) · 1.66 KB
/
03_fastapi_server.py
File metadata and controls
59 lines (41 loc) · 1.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
"""Example 3: FastAPI server with Bearer token validation.
Every protected route requires a valid Bearer token issued by AuthGate.
Optional scope enforcement is shown on /admin.
Install extras:
uv pip install authgate[fastapi]
Run:
uv run uvicorn examples.03_fastapi_server:app --reload
"""
from __future__ import annotations
import os
from fastapi import Depends, FastAPI
from authgate.discovery.client import DiscoveryClient
from authgate.middleware.fastapi import BearerAuth
from authgate.middleware.models import TokenInfo
from authgate.oauth.client import OAuthClient
AUTHGATE_URL = os.environ["AUTHGATE_URL"]
CLIENT_ID = os.environ["AUTHGATE_CLIENT_ID"]
# Build shared OAuth client once at startup.
_meta = DiscoveryClient(AUTHGATE_URL).fetch()
_oauth = OAuthClient(CLIENT_ID, _meta.to_endpoints())
# Reusable dependency — validates any Bearer token.
bearer_auth = BearerAuth(_oauth)
# Dependency that also enforces a specific scope.
admin_auth = BearerAuth(_oauth, required_scopes=["admin"])
app = FastAPI(title="AuthGate FastAPI Example")
@app.get("/me")
async def get_me(token_info: TokenInfo = Depends(bearer_auth)) -> dict[str, object]:
"""Return the token's subject and scopes."""
return {
"sub": token_info.sub,
"scopes": token_info.scopes,
"active": token_info.active,
}
@app.get("/admin")
async def admin_endpoint(token_info: TokenInfo = Depends(admin_auth)) -> dict[str, str]:
"""Only accessible with the 'admin' scope."""
return {"message": f"Hello admin {token_info.sub}!"}
@app.get("/health")
async def health() -> dict[str, str]:
"""Public endpoint — no auth required."""
return {"status": "ok"}