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
import os
from typing import Annotated

from fastapi import FastAPI
from ska_aaa_authhelpers import (
    AuditLogFilter,
    AuthContext,
    AuthFailError,
    Requires,
    Role,
    watchdog,
)
from ska_ser_logging import configure_logging

# Adds user_id and trace metadata to application logs for auditing:
configure_logging(level="INFO", tags_filter=AuditLogFilter)

API_CODENAME = "farm"
# Default to 'live' because it's annoying but safe if your
# test deployment rejects your test tokens.
# Much worse if your live production system accepts test tokens.
DEFAULT_AUDIENCE = f"live:{API_CODENAME}"
# Configure at runtime export AUDIENCE="test:farm"
AUDIENCE = os.environ.get("AUDIENCE", DEFAULT_AUDIENCE)

# Your API must define its own scopes and register them with Indigo.
GET_FRUIT_SCOPE = f"{API_CODENAME}:fruits:pick"

# From your database or configuration...
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=AUDIENCE)


@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!")