Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Prepare applications for Azure deployment by generating infrastructure code, Dockerfiles, and config files.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
references/services/app-service/templates/recipes/auth/source/python.md
1# Auth Recipe — Python (FastAPI) — REFERENCE ONLY23## JWT Validation with PyJWT45### Requirements67Add to `requirements.txt`:89```10PyJWT[crypto]>=2.811cryptography12fastapi13uvicorn14```1516### Token Validation Middleware1718Add `auth.py`:1920```python21import os22from fastapi import Depends, HTTPException23from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials24import jwt25from jwt import PyJWKClient2627security = HTTPBearer()28TENANT_ID = os.environ["AZURE_TENANT_ID"]29CLIENT_ID = os.environ["AZURE_CLIENT_ID"]30# Use APP_ID_URI if set (e.g., "api://<client-id>"); fall back to CLIENT_ID31AUDIENCE = os.environ.get("AZURE_APP_ID_URI", CLIENT_ID)32JWKS_URL = f"https://login.microsoftonline.com/{TENANT_ID}/discovery/v2.0/keys"3334jwks_client = PyJWKClient(JWKS_URL)3536async def validate_token(creds: HTTPAuthorizationCredentials = Depends(security)):37try:38signing_key = jwks_client.get_signing_key_from_jwt(creds.credentials)39payload = jwt.decode(40creds.credentials,41signing_key.key,42algorithms=["RS256"],43audience=AUDIENCE,44issuer=f"https://login.microsoftonline.com/{TENANT_ID}/v2.0",45)46return payload47except jwt.InvalidTokenError:48raise HTTPException(status_code=401, detail="Invalid token")49```5051> ⚠️ The `aud` claim in Entra ID tokens is often the Application ID URI (`api://<client-id>`), not the raw client ID. Set `AZURE_APP_ID_URI` in app settings to match your app registration's exposed API URI.5253### Protected Endpoint5455Add to `main.py`:5657```python58from auth import validate_token5960@app.get("/api/me")61async def me(user=Depends(validate_token)):62return {"name": user.get("name"), "oid": user.get("oid")}63```6465## App Settings Required6667| Setting | Value |68|---------|-------|69| `AZURE_TENANT_ID` | Entra tenant ID |70| `AZURE_CLIENT_ID` | App registration client ID |71| `AZURE_APP_ID_URI` | Application ID URI (e.g., `api://<client-id>`) — optional, defaults to CLIENT_ID |7273## Files to Modify7475| File | Action |76|------|--------|77| `auth.py` | Create — JWT validation middleware |78| `main.py` | Modify — add protected endpoints |79| `requirements.txt` | Modify — add PyJWT, cryptography |80