Skip to content

🔌 Framework Integration

jwtlib is intentionally framework-agnostic. This page shows the idiomatic wiring used by the canonical auth-server service.


⚙️ FastAPI dependency

Expose the token from the Authorization header and resolve it to a user via a dependency:

from fastapi import Depends, FastAPI, HTTPException, status
from jwtlib import get_logged_in_user
from jwtlib.exceptions import AuthError

app = FastAPI()


def bearer_token(authorization: str = Header(...)) -> str:
    scheme, _, token = authorization.partition(" ")
    if scheme.lower() != "bearer" or not token:
        raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Invalid authorization header")
    return token


async def current_user(token: str = Depends(bearer_token)):
    try:
        return await get_logged_in_user(token)
    except AuthError:
        raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Not authenticated")


@app.get("/me")
async def me(user=Depends(current_user)):
    return {"username": user.username, "email": user.email}

On any auth failure the dependency translates AuthError into a 401 — the library never couples to the HTTP layer.


📡 Resource server / microservice

A consumer service that does not own the user database can verify tokens via introspection without a shared session store:

1
2
3
4
5
6
7
8
from jwtlib.introspection import authenticate_request


async def is_allowed(authorization: str) -> bool:
    scheme, _, token = authorization.partition(" ")
    if scheme.lower() != "bearer":
        return False
    return await authenticate_request(token)

🧭 Routing tokens

  • First-party services — use get_logged_in_user (and the TOKEN_SECRET_KEY they share) for a direct lookup.
  • Third-party / external clients — validate against the auth-server/introspect endpoint for a standard introspection response.
  • Static vetoes — use authenticate_request when you only need allow/deny.

Keep Authorization: Bearer <token> consistent across all callers.


⚠️ Error mapping cheat-sheet

Raised exception Typical HTTP result
InvalidAuthorizationHeader 401 — malformed header
InvalidToken 401 — expired, bad signature, or malformed
UserNotFound 401 — subject no longer exists
AuthServiceUnavailable 503 — upstream auth unavailable
NotAuthenticated 401 — missing credentials