Python Backend Example
This page is the same check as the Go example, for a FastAPI backend. APP_SECTOR_ID is the app sector from the dashboard, not the organization Sector ID from signup. A token for another app in the same organization still returns HTTP 200.
A missing token, a non-200 introspect response, or the wrong sector is HTTP 401. A network or decode failure is HTTP 500. That failure is not a successful login.
exp and iat arrive as quoted strings. Convert them with int before you compare them to a timestamp.
from typing import Optional
import httpxfrom fastapi import Depends, FastAPI, HTTPException, Request
APP_SECTOR_ID = "your-app-sector-id"INTROSPECT_URL = "https://api.spartanauth.com/api/v1/introspect"
app = FastAPI()
async def introspect_token(token: str) -> Optional[dict]: """Return the user, or None when SpartanAuth rejects the token.""" try: async with httpx.AsyncClient(timeout=5) as client: resp = await client.post(INTROSPECT_URL, json={"token": token}) except httpx.HTTPError as exc: raise HTTPException(status_code=500, detail="authentication error") from exc if resp.status_code != 200: return None try: user = resp.json() user["exp"] = int(user["exp"]) user["iat"] = int(user["iat"]) except (ValueError, KeyError, TypeError) as exc: raise HTTPException(status_code=500, detail="authentication error") from exc return user
async def require_user(request: Request) -> dict: header = request.headers.get("authorization", "") token = header.removeprefix("Bearer ") if header.startswith("Bearer ") else "" if not token: raise HTTPException(status_code=401, detail="missing token") user = await introspect_token(token) if user is None or user.get("sectorID") != APP_SECTOR_ID: raise HTTPException(status_code=401, detail="invalid token") return user
@app.get("/profile")async def profile(user: dict = Depends(require_user)) -> dict: return {"sub": user["sub"]}Install the HTTP client with pip install httpx. The dependency runs before the route. Another Python framework should make the same POST and return 401 or 500 before the view runs.