Skip to main content

ruscker-sso (Python)

Sign people in to a Python backend through a Ruscker portal ("Sign in with …"). A thin wrapper over PyJWT and httpx pre-set for the provider's profile: authorization code + PKCE, ID tokens signed with ES256 only. It follows the contract shared by every client package.

Two calls do the work: start_sign_in() builds the URL to send the browser to, and finish_sign_in() checks the callback, redeems the code and verifies the ID token, in that order. The package does not keep sessions: after a sign-in, the application issues its own.

Install

Python 3.10 or later.

pip install ruscker-sso          # or: uv add ruscker-sso

Example: FastAPI

The three pending values live in Starlette's signed session cookie for the few minutes between the two routes (pip install fastapi uvicorn itsdangerous).

import os

from fastapi import FastAPI, Request
from fastapi.responses import RedirectResponse
from starlette.middleware.sessions import SessionMiddleware

from ruscker_sso import PendingSignIn, RusckerSSO, SignInError

sso = RusckerSSO(
    issuer="https://portal.example.org",
    client_id="my-system",
    client_secret=os.environ["RUSCKER_CLIENT_SECRET"],
    redirect_uri="https://app.example.org/auth/callback",
)

app = FastAPI()
# Signed (not encrypted) cookie, HttpOnly; https_only in production.
app.add_middleware(SessionMiddleware, secret_key=os.environ["APP_SESSION_KEY"],
                   https_only=True, same_site="lax")


@app.get("/auth/login")
def login(request: Request):
    sign_in = sso.start_sign_in()
    request.session["ruscker_pending"] = sign_in.pending.to_json()
    return RedirectResponse(sign_in.url)


@app.get("/auth/callback")
def callback(request: Request):
    stored = request.session.pop("ruscker_pending", None)   # single use
    if stored is None:
        return RedirectResponse("/auth/login")
    try:
        person = sso.finish_sign_in(request.query_params, PendingSignIn.from_json(stored))
    except SignInError as exc:
        return RedirectResponse(f"/?signin_failed={type(exc).__name__}")
    # The application's own session from here on. Key the account by `sub`.
    request.session["user"] = {"sub": person.sub, "name": person.name,
                               "is_manager": person.has_role("fiscal", "gestor")}
    return RedirectResponse("/")

The calls are synchronous (they make two short HTTP requests on the first sign-in, then one); FastAPI runs a plain def route in a thread pool. The same two calls work in Flask (session, request.args) and Django (request.session, request.GET): store pending.to_json(), then pass the query and PendingSignIn.from_json(...) back.

Create one RusckerSSO at start-up and share it: it caches the discovery document and the keys, and is thread-safe. Pass http_client=httpx.Client(...) for proxies or a custom CA bundle.

Signing out, the password page, silent checks

Since 0.2.0.

sso.sign_out_url(*, post_logout_redirect_uri=None, state=None, id_token_hint=None) builds the address of the portal's sign-out page. End the application's own session first, then redirect there: the portal asks the person before ending its session and sends the browser back to post_logout_redirect_uri (with state, at most 512 characters). That address must be one of the client's Return addresses after sign-out on the portal, exactly. The endpoint comes from the cached discovery document; a portal that does not announce one is older than this feature and the call raises SignInError.

@app.get("/auth/logout")
def logout(request: Request):
    request.session.clear()                          # the app's own session first
    return RedirectResponse(sso.sign_out_url(
        post_logout_redirect_uri="https://app.example.org/signed-out"))

sso.password_change_url() returns {issuer}/admin/account/password?client_id=…, with no network call. The portal signs the person in if needed and its page links back to the client's System address:

@app.get("/account/password")
def change_password():
    return RedirectResponse(sso.password_change_url())

sso.start_sign_in(prompt="none") asks the portal not to show a sign-in page: a person still signed in there comes straight back with a code, and anyone else comes back with error=login_required (ProviderError). Use it when the application's own session expires, to notice that the portal session ended.

The identity

Attribute Claim Notes
sub sub permanent id. The key to store
username preferred_username None without the profile scope
name name full name, or the username
email email may be None
setor setor department; may be None
groups groups list; only the groups that give access to this system when it is restricted
group_roles group_roles dict group → list of roles; {} when none
claims — every claim of the verified token

Helpers: has_group(g), has_role(group, role), roles(group).

Default scopes: openid profile email groups roles setor; pass scopes=[...] to ask for less (openid is always added).

Errors

All are SignInError; catch that one for "sign-in failed".

Exception When Useful attributes
ProviderError the callback carries error= (e.g. access_denied: not in the system's groups) code, description
StateMismatchError state differs from the stored one; nothing was sent to the provider
IssuerMismatchError the callback's iss, or the discovery document's issuer, is not the configured issuer expected, got, where
TokenExchangeError the token endpoint refused the code (invalid_grant: used, expired, other verifier; invalid_client: wrong secret) status, error, description
InvalidIDTokenError the ID token failed verification reason: signature, algorithm, audience, issuer, expired, not_yet_valid, nonce, missing_claim, unknown_key, malformed, claims
SignInError itself provider unreachable, malformed response, no code, unreadable stored values

A code works once. Whatever the outcome, start a new sign-in rather than retrying.

Tests

cd clients/python
uv run --with pytest --with-editable . pytest            # unit tests, no network

The end-to-end test runs against a real provider started with clients/testing/provider.sh (see the testing notes) and is skipped when RUSCKER_ISSUER is unset:

source /tmp/sso-dev/env
uv run --with pytest --with-editable . pytest -v tests/test_e2e.py

Metadata

Release files for ruscker-sso 0.2.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 ruscker-sso 0.2.0
File Size Uploaded Provenance Actions
ruscker_sso-0.2.0.tar.gz 21.5 kB With provenance Details for ruscker_sso-0.2.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for ruscker-sso 0.2.0
File Interpreter ABI Platform Actions
ruscker_sso-0.2.0-py3-none-any.whl Python 3 none any Details for ruscker_sso-0.2.0-py3-none-any.whl

Total release size: 39.8 kB

Release files / ruscker_sso-0.2.0.tar.gz

Download URL ruscker_sso-0.2.0.tar.gz
Size 21.5 kB
Tags Source
SHA-256 checksum
How to use checksums
b31cf8e96c7d31e907b64f90dd22916eba8ab189c7bec4fd715062dbff71bd25
BLAKE2b-256 checksum
How to use checksums
053235db91d6dfa135422db0976bb1651e973a769ede445b14586c62c831f634
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 19, 2026.

Transparency log

Release files / ruscker_sso-0.2.0-py3-none-any.whl

Download URL ruscker_sso-0.2.0-py3-none-any.whl
Size 18.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
7d2f3fe99fc9e5959c8baabd10e8c5552a4bbf8950f383263c05e1eb1c08f4d1
BLAKE2b-256 checksum
How to use checksums
720e47ab2f74097e4f999988bbb61b883a6bb001ed83fd0b33ccb4a344d74cce
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 19, 2026.

Transparency log

Security for ruscker-sso 0.2.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 ruscker_sso-0.2.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 19, 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.

Release history Release notifications | RSS feed

This release

0.2.0 This release

2 release files Full provenance

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