Cheatsheet π€ο
If youβre in a hurry, hereβs a concise copy-paste example showing how to use ska_aaa_authhelpers in your application.
""" "Sample usage of ska_aaa_authhelpers"""
import functools
from typing import Annotated
from fastapi import FastAPI
from ska_ser_logging import configure_logging
from ska_aaa_authhelpers import (
AuditLogFilter,
AuthContext,
AuthFailError,
Requires,
Role,
watchdog,
)
# Adds user_id and trace metadata to application logs for auditing:
configure_logging(level="INFO", tags_filter=AuditLogFilter)
# Get this when registering your API with Entra ID.
YOUR_API_ID = "api://3688e6c2-87c0-4584-a674-c11e63e9b442"
# Your API must define its own scopes and register them with Entra.
GET_FRUIT_SCOPE = "fruits:pick"
APPLE_LOVERS = {
"f1bbdbe5-47c9-4dd8-896f-6aebeb0af828",
"f4b8a92b-2357-435e-9d5b-0211e08a1210",
}
# Add the watchdog to double-check all your API endpoints are secured.
app = FastAPI(lifespan=watchdog())
# Purely optional: use partial() to avoid repeating 'audience' on every route.
Permissions = functools.partial(Requires, audience=YOUR_API_ID)
@app.get("/apple")
async def pick_apple(
# https://fastapi.tiangolo.com/tutorial/dependencies/
# Adds AuthContext as a parameter to your functions:
auth: Annotated[
AuthContext,
Permissions(
roles={Role.SW_ENGINEER},
scopes={GET_FRUIT_SCOPE},
),
],
):
if auth.principals.intersection(APPLE_LOVERS):
return {"message": f"{auth.user_id} gets an apple"}
else:
raise AuthFailError("Only apple-lovers allowed here!")