Leantel

Quickstart: Python (FastAPI)

A FastAPI app that signs people in with Leantel, protects an API route, and receives webhooks. Tested with Python 3.14, FastAPI, Authlib 1.8, PyJWT 2 and httpx2. Read auth.md for an explanation of each step. Using Flask or Django? Authlib has integrations for both; the parameters and checks stay the same.

1. Set up

In the Leantel console, create a Web app with a backend. Register https://<your app>/callback as a redirect URL and https://<your app>/ as a sign-out redirect URL. To try it on your computer first, also register http://localhost:<port> versions of both URLs: Leantel accepts exact http://localhost and http://127.0.0.1 URLs for apps with a backend, and for single-page apps in development workspaces; the port must match exactly. Then:

requirements.txt
fastapi
uvicorn
authlib
httpx2
itsdangerous
pyjwt[crypto]
python-dotenv
python3 -m venv .venv && .venv/bin/pip install -r requirements.txt
.env.example
LEANTEL_ISSUER=
LEANTEL_CLIENT_ID=
LEANTEL_CLIENT_SECRET=
LEANTEL_REDIRECT_URI=
LEANTEL_POST_LOGOUT_URI=
LEANTEL_AUDIENCE=
LEANTEL_WEBHOOK_SECRET=
SESSION_SECRET=
APP_API_URL=

2. Sign in and out

app/sign_in.py
import os
import secrets
import time
from urllib.parse import urlencode

from authlib.integrations.starlette_client import OAuth, OAuthError
from fastapi import APIRouter, Request
from fastapi.responses import PlainTextResponse, RedirectResponse

oauth = OAuth()
oauth.register(
    name="leantel",
    server_metadata_url=f"{os.environ['LEANTEL_ISSUER']}/.well-known/openid-configuration",
    client_id=os.environ["LEANTEL_CLIENT_ID"],
    client_secret=os.environ["LEANTEL_CLIENT_SECRET"],
    client_kwargs={"scope": "openid email", "code_challenge_method": "S256"},
)

router = APIRouter()
token_store: dict[str, dict] = {}


@router.get("/login")
async def login(request: Request, signup: str = ""):
    extra = {"prompt": "create"} if signup == "1" else {}
    return await oauth.leantel.authorize_redirect(request, os.environ["LEANTEL_REDIRECT_URI"], **extra)


@router.get("/callback")
async def callback(request: Request):
    try:
        token = await oauth.leantel.authorize_access_token(request)
    except OAuthError:
        return PlainTextResponse("Sign-in failed or expired. Try again.", status_code=400)
    claims = token["userinfo"]
    token_key = secrets.token_urlsafe(32)
    token_store[token_key] = {
        "access_token": token["access_token"],
        "refresh_token": token.get("refresh_token"),
        "expires_at": time.time() + token.get("expires_in", 0),
    }
    request.session.clear()
    request.session["user"] = {"user_id": claims["sub"], "tenant_id": claims["tenant_id"], "id_token": token["id_token"], "token_key": token_key}
    return RedirectResponse("/", status_code=302)


async def access_token(request: Request) -> str | None:
    token_key = request.session.get("user", {}).get("token_key", "")
    stored = token_store.get(token_key)
    if not stored:
        return None
    if time.time() < stored["expires_at"] - 30:
        return stored["access_token"]
    if not stored["refresh_token"]:
        return None
    try:
        refreshed = await oauth.leantel.fetch_access_token(grant_type="refresh_token", refresh_token=stored["refresh_token"])
    except OAuthError:
        token_store.pop(token_key, None)
        return None
    token_store[token_key] = {
        "access_token": refreshed["access_token"],
        "refresh_token": refreshed.get("refresh_token", stored["refresh_token"]),
        "expires_at": time.time() + refreshed.get("expires_in", 0),
    }
    return refreshed["access_token"]


@router.get("/logout")
async def logout(request: Request):
    user = request.session.get("user", {})
    token_store.pop(user.get("token_key", ""), None)
    id_token = user.get("id_token", "")
    request.session.clear()
    metadata = await oauth.leantel.load_server_metadata()
    query = urlencode({"id_token_hint": id_token, "post_logout_redirect_uri": os.environ["LEANTEL_POST_LOGOUT_URI"]})
    return RedirectResponse(f"{metadata['end_session_endpoint']}?{query}", status_code=302)

/login?signup=1 opens the sign-up page instead. Authlib adds PKCE (S256), state and nonce, and checks them on the callback; token["userinfo"] holds the verified ID token claims. The session cookie is signed but readable, so tokens go in token_store on the server and the cookie keeps only a random key. access_token refreshes an expired access token and saves the rotated refresh token; reusing an old one signs the person out. In production, use your database or cache.

3. Protect an API route

app/api.py
import os

import jwt
from fastapi import Depends, Header, HTTPException

issuer = os.environ["LEANTEL_ISSUER"]
keys = jwt.PyJWKClient(f"{issuer}/.well-known/jwks.json", cache_keys=True)


def access_claims(authorization: str = Header(default="")) -> dict:
    token = authorization.removeprefix("Bearer ") if authorization.startswith("Bearer ") else ""
    try:
        signing_key = keys.get_signing_key_from_jwt(token)
        claims = jwt.decode(
            token,
            signing_key.key,
            algorithms=["RS256"],
            issuer=issuer,
            audience=os.environ["LEANTEL_AUDIENCE"],
            leeway=60,
            options={"require": ["exp", "iat", "sub", "jti", "client_id", "tenant_id"]},
        )
        if jwt.get_unverified_header(token).get("typ") != "at+jwt":
            raise jwt.InvalidTokenError("not an access token")
    except jwt.PyJWTError:
        raise HTTPException(status_code=401, detail="Invalid token", headers={"WWW-Authenticate": 'Bearer error="invalid_token"'})
    return claims


def require_permission(permission: str):
    def check(claims: dict = Depends(access_claims)) -> dict:
        if permission not in claims.get("scope", "").split():
            raise HTTPException(
                status_code=403,
                detail=f"Missing permission {permission}",
                headers={"WWW-Authenticate": 'Bearer error="insufficient_scope"'},
            )
        return claims

    return check

PyJWT checks the signature, algorithm, issuer, audience and expiry; the extra line rejects anything that isn't an access token (typ: at+jwt). A bad or missing token gets 401.

To require a permission on a route, use Depends(require_permission("app:use")) in place of Depends(access_claims); a token without the permission gets 403. Set up Auth gives your workspace the permission app:use and the role member, which everyone who signs up gets; add your own permissions under APIs and permissions and grant them through roles (auth.md section 7).

4. Receive webhooks

app/webhook.py
import hashlib
import hmac
import json
import os
import time

from fastapi import APIRouter, Request, Response


def is_valid_signature(header: str, body: bytes, secret: str, now: float | None = None) -> bool:
    parts = dict(part.split("=", 1) for part in header.split(",") if "=" in part)
    timestamp = parts.get("t", "")
    if not timestamp.isdigit() or abs((now or time.time()) - int(timestamp)) > 300:
        return False
    expected = hmac.new(secret.encode(), f"{timestamp}.".encode() + body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, parts.get("v1", ""))


router = APIRouter()
handled_event_ids: set[str] = set()


@router.post("/webhooks/leantel")
async def receive(request: Request) -> Response:
    body = await request.body()
    if not is_valid_signature(request.headers.get("Auth-Signature", ""), body, os.environ["LEANTEL_WEBHOOK_SECRET"]):
        return Response("Invalid signature", status_code=401)
    event = json.loads(body)
    if event["id"] not in handled_event_ids:
        handled_event_ids.add(event["id"])
        print("leantel event", event["type"], event["id"])
    return Response(status_code=200)

5. Wire it up

app/main.py
import os

import httpx2
from fastapi import Depends, FastAPI, Request
from fastapi.responses import HTMLResponse, Response
from starlette.middleware.sessions import SessionMiddleware

from app import sign_in, webhook
from app.api import access_claims

app = FastAPI()
app.add_middleware(SessionMiddleware, secret_key=os.environ["SESSION_SECRET"], same_site="lax", https_only=os.environ["LEANTEL_REDIRECT_URI"].startswith("https://"))
app.include_router(sign_in.router)
app.include_router(webhook.router)


@app.get("/")
async def home(request: Request):
    token = await sign_in.access_token(request)
    if not token:
        return HTMLResponse('<a href="/login">Sign in</a>')
    async with httpx2.AsyncClient() as client:
        api = await client.get(f"{os.environ['APP_API_URL']}/api/me", headers={"Authorization": f"Bearer {token}"})
    return Response(api.content, status_code=api.status_code, media_type="application/json")


@app.get("/api/me")
def me(claims: dict = Depends(access_claims)):
    return {"tenant_id": claims["tenant_id"], "user_id": claims["sub"]}

The signed session cookie only holds the user's IDs. The in-memory set of handled event IDs is for trying it out; record them in your database in production.

6. Check it works

  • .venv/bin/uvicorn app.main:app --env-file .env, open /login: you land on your branded Leantel sign-in page, then back on /, which calls your API's /api/me with the access token and shows your tenant_id and user_id. Set APP_API_URL to your app's own URL.
  • curl -i https://<your app>/api/me (no token) → 401.
  • In the console, Webhooks → Send test event → your log shows it.