Skip to main content

galeo

Verify Galeo access tokens in Python services, map Galeo roles onto your own, and test all of it without a network.

It's the backend half of adding "Sign in with Galeo" to an app. The frontend half is @galeo/react, which signs the user in and sends their access token on every API call.

pip install "galeo[fastapi]"

Configure

Two values, both from the application's page in the Galeo admin console:

GALEO_ISSUER https://<host>/auth/<organization>, for the host your users sign in on
GALEO_CLIENT_ID The application's client ID

GALEO_SCOPE is optional and defaults to openid profile email groups. GALEO_INTROSPECT, GALEO_CLIENT_SECRET and GALEO_CLIENT_AUTH_METHOD are optional too; see Cutting off blocked users.

from galeo import GaleoConfig

config = GaleoConfig.from_env()
# or GaleoConfig(issuer="https://login.example.com/auth/acme", client_id="…")

FastAPI

from fastapi import Depends, FastAPI
from galeo import GaleoConfig, Principal
from galeo.fastapi import Galeo

app = FastAPI()
galeo = Galeo(GaleoConfig.from_env())

# GET /auth/config: what the frontend needs to start sign-in.
app.include_router(galeo.config_router())


@app.get("/me")
def me(principal: Principal = Depends(galeo.principal)):
    return {"id": principal.subject, "email": principal.email, "roles": sorted(principal.roles)}


@app.delete("/projects/{project_id}")
def delete_project(
    project_id: str, principal: Principal = Depends(galeo.require_role("admin"))
): ...
  • galeo.principal answers 401 with an RFC 6750 WWW-Authenticate challenge when the token is missing or invalid.
  • If Galeo can't be reached and no signing keys are cached yet, it answers 503. That's an outage, not a bad token, so clients retry instead of signing the user out.
  • galeo.optional_principal returns None when there's no token.
  • galeo.require_role(...) answers 403 unless the user holds one of the roles.

WebSockets

Browsers can't set Authorization on a WebSocket, so send the token as a subprotocol with new WebSocket(url, ["bearer", token]):

@app.websocket("/ws")
async def ws(websocket: WebSocket):
    principal = await galeo.websocket_principal(websocket)  # closes with 1008 if invalid
    await websocket.accept(subprotocol="bearer")

What gets checked

TokenVerifier.verify(token) accepts a token only if all of these hold:

  • Signature: checked with the key its kid names; RS256 only.
  • Token type: typ is at+jwt. Galeo's ID tokens are signed with the same key and carry the same sub and aud, so they're refused here.
  • Issuer: iss is your organization's issuer.
  • Audience: aud is your client ID. Every app in the organization shares the issuer and signing key, so without this check another app's token would pass, carrying the roles it holds in that other app.
  • Validity window: exp and nbf are current, allowing 30 seconds of skew.

Galeo's discovery document and keys are cached for as long as Galeo's Cache-Control allows.

  • Unknown kid: a token naming a key the cache doesn't have triggers a refetch, but at most once a minute, so garbage tokens can't make your service hammer Galeo.
  • Outages: if Galeo is unreachable, the last keys fetched stay in use.

Cutting off blocked users

All of the checks above run in your service, without asking Galeo. So a token keeps working until it expires (60 minutes by default) even after Galeo has blocked its user. Introspection closes that window: once a token passes the local checks, the SDK also asks Galeo's introspection endpoint whether it's still active.

Galeo reports a token inactive once:

  • the user is disabled, put on a security hold (for example, after being marked compromised), or their account expires;
  • the application is deactivated.

Introspection doesn't catch everything. A user who only signed out, or whose session an admin ended, still has an active token. A token's roles also stay as they were when it was issued.

Turn it on for every route:

galeo = Galeo(GaleoConfig.from_env())  # with GALEO_INTROSPECT=true
# or GaleoConfig(issuer=..., client_id=..., introspect=True)

Or only where it matters:

@app.post("/payouts")
def payout(principal: Principal = Depends(galeo.active_principal)): ...


@app.delete("/projects/{project_id}")
def delete_project(
    project_id: str, principal: Principal = Depends(galeo.require_role("admin", introspect=True))
): ...

TokenVerifier.verify(token, introspect=True) and galeo.websocket_principal(websocket, introspect=True) do the same. A WebSocket is checked once, at the handshake. introspect=False turns it off for one call when it's on for the app.

  • Cost: one call to Galeo per token every introspection_cache_seconds (default 30). The cache is also the longest a blocked user keeps access. Set it to 0 to ask on every request. Tokens that fail the local checks never reach Galeo.
  • A blocked user gets 401 error="invalid_token", error_description="token is no longer active".
  • Outages fail closed. If Galeo can't be reached, or answers 5xx or 429, the request gets 503, so clients retry instead of signing the user out. Failures aren't cached.
  • Client authentication: a public client (token auth method none, the usual setup with @galeo/react) sends only its client ID. A confidential client sets GALEO_CLIENT_SECRET, and GALEO_CLIENT_AUTH_METHOD if the application uses client_secret_post instead of the default client_secret_basic. If Galeo refuses the credentials, verification raises ConfigurationError (a 500), not a 401.

Requiring MFA

galeo.require_aal(level) admits only users who signed in at that assurance level or higher. Level 2 needs a second factor or a passkey, and level 3 a smart card.

@app.post("/payouts")
def payout(principal: Principal = Depends(galeo.require_aal(2))): ...

Anyone below the level gets 401 with the RFC 9470 challenge error="insufficient_user_authentication", with the level wanted in acr_values. @galeo/react reads it with stepUpRequired(response), and signIn({ aal }) sends the user back through Galeo to sign in again at that level. Refreshing the token doesn't help, because a refreshed token keeps the level of the original sign-in. A user with no second factor set up comes back at level 1 and is refused again, so the frontend should offer the step-up rather than force it.

require_aal takes introspect= like require_role. To require a role and a level together, add both dependencies.

The Principal

subject The user's Galeo ID. Stable for the life of the account.
key (issuer, subject). Key your local user records on this, not on email. An email can change, and a different account can later hold it.
email, name With the email / profile scopes
roles The user's role names in your application, from the groups claim. Not directory groups. Narrowed to the chosen role if the app makes users pick one at sign-in. Always empty on Identity Platform plans, because roles need Identity Governance: require_role then always answers 403, and RoleMapper gives its default.
scopes Granted scopes
aal, acr The assurance level the sign-in reached: aal is 1 to 3, or 0 when the token states none (client credentials tokens), and acr is the claim itself, one of galeo.ACR_AAL1 to ACR_AAL3
amr How the user signed in (RFC 8176), e.g. {"pwd", "otp"}
claims, token The raw claims and token

Creating local users on first sign-in

def current_user(
    principal: Principal = Depends(galeo.principal), db: Session = Depends(get_db)
) -> User:
    user = (
        db.query(User)
        .filter_by(galeo_issuer=principal.issuer, galeo_subject=principal.subject)
        .one_or_none()
    )
    if user is None:
        user = User(galeo_issuer=principal.issuer, galeo_subject=principal.subject)
        db.add(user)
    user.email, user.name = principal.email, principal.name
    user.role = roles.resolve(principal.roles)
    db.commit()
    return user

Service-to-service calls

A service running on a platform Galeo trusts gets its own Galeo access tokens without storing a secret. An admin registers the platform's OIDC issuer (an EKS cluster's, say) as a workload issuer in Galeo, creates a service identity for the workload's subject (system:serviceaccount:default:trevor), and grants it roles in the applications it calls, as for a person.

The calling service exchanges its platform token for a Galeo token (RFC 8693):

import galeo

# Reads GALEO_ISSUER and the projected token at GALEO_WEB_IDENTITY_TOKEN_FILE
# (default /var/run/secrets/galeo/token); caches until shortly before expiry.
token = galeo.service_token(audience=PRISM_CLIENT_ID)
httpx.get(f"{PRISM}/api/search", headers={"Authorization": f"Bearer {token}"})

On Kubernetes, mount a projected service account token whose audience is the one the workload issuer expects:

volumes:
  - name: galeo-token
    projected:
      sources:
        # the issuer's audience; by default your Galeo issuer URL
        - serviceAccountToken: {path: token, audience: "https://login.example.com/auth/acme", expirationSeconds: 3600}

The receiving service verifies the token like any other. It has sub = svc:<id>, no email or name, and the service's roles in groups. principal.is_service tells a service from a person, so don't provision it as a user:

if principal.is_service:
    ...  # authorize on principal.roles; there is no email to key a local account on

Disabling the service identity or revoking its last role in the application makes introspection report its tokens inactive at once.

Mapping roles

from galeo import RoleMapper

roles = RoleMapper(
    {"admin": "admin", "program-lead": "lead"},  # Galeo role -> your role
    ranking=["admin", "lead", "contributor"],  # most to least privileged
    default="contributor",
)
roles.resolve(principal.roles)  # "admin", "lead" or "contributor"

Resolve on every sign-in and store the result. Don't only ever raise a stored role: someone removed from a role in Galeo has to lose it in your app too.

Testing your app

import pytest
from galeo.testing import FakeGaleo
from myapp.main import app, galeo


@pytest.fixture
def fake_galeo():
    fake = FakeGaleo(client_id="my-app")
    fake.install(galeo)  # the app's Galeo now trusts the fake's tokens
    return fake


def test_me(fake_galeo):
    token = fake_galeo.access_token(roles=["admin"], email="ada@example.test")
    res = TestClient(app).get("/me", headers={"Authorization": f"Bearer {token}"})
    assert res.json()["roles"] == ["admin"]

FakeGaleo serves discovery, JWKS and introspection in memory, so the real verification path runs. To build tokens that must be refused, push an argument out of range:

  • expires_in=-60 for an expired token
  • audience="another-app" for another app's token
  • typ="JWT" for an ID token

aal= sets the level the sign-in reached (default 1). aal=2 makes an MFA sign-in, and aal=None makes a token with no level, like a client credentials token.

rotate_key() simulates a key rotation. block_user(subject) makes introspection report that user's tokens inactive, as Galeo does after disabling them, and unblock_user(subject) reverses it. install() keeps your app's introspect setting. Pass client_secret= to FakeGaleo to test a confidential client.

Development

pip install -e ".[dev]"
pytest
ruff check . && mypy

Metadata

Release files for galeo 0.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for galeo 0.3.0
File Size Uploaded Provenance Actions
galeo-0.3.0.tar.gz 35.2 kB With provenance Details for galeo-0.3.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for galeo 0.3.0
File Interpreter ABI Platform Actions
galeo-0.3.0-py3-none-any.whl Python 3 none any Details for galeo-0.3.0-py3-none-any.whl

Total release size: 68.2 kB

Release files / galeo-0.3.0.tar.gz

Download URL galeo-0.3.0.tar.gz
Size 35.2 kB
Tags Source
SHA-256 checksum
How to use checksums
b7bbedb1eafe378781c9453d4877ee3cd2a0e885654ea2fc51b13a475fc0d4dc
BLAKE2b-256 checksum
How to use checksums
d07ca817282ef791f35a90a91a7e86e4070c580008ee304927f761c2ed0c7c88
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 20, 2026.

Transparency log

Release files / galeo-0.3.0-py3-none-any.whl

Download URL galeo-0.3.0-py3-none-any.whl
Size 33.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
61333b64b3a1759e0d728d06f5a18ba0a4e42d9ce9ab0bb21a418836f7ead4e9
BLAKE2b-256 checksum
How to use checksums
d3b19ea8c68e3ad3728515fcd64a369236d6d4a92499f17117878df3478dbad4
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 20, 2026.

Transparency log

Security for galeo 0.3.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for galeo-0.3.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 20, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page