Skip to main content

litestar-oauth-server

Add OAuth 2.1 to a Litestar app: PKCE, client registration, token and refresh, plus the metadata MCP clients need.

PyPI Python versions Docs Pipeline License: MIT

Docs · API reference · Changelog


Overview

litestar-oauth-server is a plugin for Litestar. It adds the OAuth 2.1 routes: the token endpoint (authorization code with PKCE, refresh), revocation, client registration and the device grant. It also serves the metadata documents MCP clients use for discovery. Your app provides the login, the consent screen and the database.

Status: beta.

Install

pip install litestar-oauth-server

Requires Python 3.12+. For stores on Postgres, add the extra and a Postgres driver:

pip install "litestar-oauth-server[sqlalchemy]" "psycopg[binary]"

Quickstart

from litestar import Litestar, Request, get
from litestar_oauth_server import (
    AuthorizationServer, LitestarOAuth, OAuthConfig, bearer_guard, in_memory_stores, verified_token,
)

RESOURCE = "https://api.example.com/mcp"

server = AuthorizationServer(
    config=OAuthConfig(
        issuer="https://api.example.com",
        authorization_endpoint="https://app.example.com/oauth/authorize",  # your consent page
        resources=(RESOURCE,),
        scopes_supported=("things:read", "things:write"),
    ),
    stores=in_memory_stores(),  # use stores on your own database in production
)

@get("/mcp", guards=[bearer_guard(server, RESOURCE, scope="things:read")])
async def things(request: Request) -> str:
    token = verified_token(request)  # subject, binding, scopes
    return f"hello {token.subject}, pinned to {token.binding}"

app = Litestar([things], plugins=[LitestarOAuth(server)])

Your consent page signs the user in with your own login, then calls server.approve(request, Approval(subject=..., scopes=..., binding=...)) and sends the browser to the URL it returns. See examples/basic.py.

Device login for a CLI (RFC 8628)

Use it when the client cannot open a browser callback: a CLI or a headless agent. The client shows a short code, and the user types it on a page of your app. Steps:

  1. Set OAuthConfig(device_verification_uri="https://app.example.com/device"). This is your page. The stores need devices (in_memory_stores() and sql_stores() have it).
  2. Give the client the device grant. Pre-register it, or let it register itself:
await server.add_client(
    client_name="my-cli", grant_types=("urn:ietf:params:oauth:grant-type:device_code", "refresh_token")
)

A client without this grant gets unauthorized_client. Without the rule, anyone who knows the client_id of your web client could start a device flow under its name. A device-only client needs no redirect_uris.

  1. The client calls POST /oauth/device_authorization and polls POST /oauth/token with grant_type=urn:ietf:params:oauth:grant-type:device_code. The library answers authorization_pending, slow_down, access_denied and expired_token as the RFC says.
  2. Your page signs the user in, then calls the server:
request = await server.describe_device(user_code)  # client name, scopes, resource
await server.approve_device(user_code, Approval(subject=user.id, scopes=("things:read",), binding=company))
# or: await server.deny_device(user_code)

Your page must show request.client_name and ask the user to confirm that they started the login on their own device, also when the code came in verification_uri_complete. The library cannot see wrong guesses, so rate-limit the page where users type the code. A code has 8 letters (about 34.5 bits) and lives 15 minutes (device_code_ttl).

Expired rows pile up on an open endpoint. Call await server.purge_expired_devices() from a periodic job. After it, an expired device code is answered as unknown (invalid_grant).

Stores on Postgres

litestar_oauth_server.sqlalchemy has ready stores for Postgres (SQLAlchemy 2, async). Steps:

  1. Define the four tables on your own MetaData, so your Alembic sees them. This package ships no migrations.
  2. Build the stores from your AsyncEngine.
from sqlalchemy import MetaData
from sqlalchemy.ext.asyncio import create_async_engine
from litestar_oauth_server import AuthorizationServer
from litestar_oauth_server.sqlalchemy import oauth_tables, sql_stores

metadata = MetaData()  # your app's metadata
tables = oauth_tables(metadata, prefix="oauth_")  # oauth_clients, oauth_codes, oauth_tokens
engine = create_async_engine("postgresql+psycopg://user:pass@localhost/app")
# `config` is the OAuthConfig of the Quickstart
server = AuthorizationServer(config=config, stores=sql_stores(engine, tables))

Each store method runs in its own transaction and commits. It does not join your session: if your code rolled back after a failed exchange, a used authorization code would come back to life. consume and consume_refresh are each one statement (DELETE ... RETURNING and UPDATE ... WHERE used_at IS NULL RETURNING), so two exchanges of one code cannot both succeed.

Only Postgres is supported. sql_stores raises ValueError for another database. Use in_memory_stores() in development.

Expired rows are never read again. Delete them from a periodic job, before purge_unused_clients():

await stores.delete_expired(datetime.now(UTC))

Clients without registration (Client ID Metadata Documents)

A client can send an https URL as its client_id. The server fetches the JSON document at that URL and uses it as a public client. It is off by default, because the server then makes outbound requests to URLs that strangers choose. Steps:

  1. Install the extra: pip install "litestar-oauth-server[cimd]".
  2. Set OAuthConfig(cimd_enabled=True).
  3. Read the CIMD page: what the consent page must show, the threats, and what is not defended.

Test your own stores

litestar_oauth_server.testing.CASES is a contract suite for any store: a code is consumed once, a refresh token is claimed once when two exchanges race, a family is revoked as a whole. It does not import pytest. Each case takes an empty Stores:

import pytest
from litestar_oauth_server.testing import CASES

@pytest.mark.anyio
@pytest.mark.parametrize("case", CASES, ids=lambda case: case.__name__)
async def test_my_stores(case):
    await case(await make_empty_stores())

Why litestar-oauth-server

Adding "Connect to Claude", a CLI login or a third-party integration to a Litestar API needs an OAuth 2.1 authorization server: PKCE, client registration, token and refresh, discovery documents. This library provides that part and leaves the login, the consent screen and the database to your app. It is the server side an MCP connector needs, and it works the same for any other client.

Key features

  • Authorization code flow with PKCE (S256 only), public clients, refresh token rotation.
  • Server metadata (RFC 8414), protected resource metadata (RFC 9728), dynamic client registration (RFC 7591), revocation (RFC 7009), resource indicators (RFC 8707).
  • A binding on every token: the tenant chosen on the consent screen. The token never crosses it.
  • Narrow scopes: the user approves a subset of what the client asked for (read-only first).
  • Code and refresh token are single use; a reused refresh token revokes its whole family.
  • Optional CORS on the OAuth routes only: OAuthConfig(cors_origins=("https://inspector.example",)), so a browser client can reach them. It applies when your app has no cors_config of its own.
  • A rate limit on POST /oauth/register, per client address: 20 an hour by default (register_rate_limit=("hour", 20), or None to turn it off). Behind a proxy, make the server read the forwarded address first (uvicorn: --proxy-headers --forwarded-allow-ips).
  • await server.purge_unused_clients() deletes clients older than unused_client_ttl (30 days) that no code or token refers to. Run it from your own periodic job. Your client store opts in by implementing ClientPurge.delete_unused(created_before).
  • server.list_clients() and server.delete_client(client_id) for an admin page. Your client store opts in by implementing ClientAdmin. A deleted client cannot refresh or exchange a code. Its access tokens stay valid until they expire or are revoked.
  • Device authorization grant (RFC 8628) for CLI and headless login, opt-in for each client.
  • Client ID Metadata Documents, opt-in: a client_id that is an https URL. The fetch refuses private addresses and redirects, and has a time and a size limit.
  • Stores on Postgres with SQLAlchemy (extra sqlalchemy), and a contract test suite for your own.
  • A bearer guard that answers 401 with WWW-Authenticate: Bearer resource_metadata=....
  • Importing the package does not import Litestar: the models, the stores and AuthorizationServer work in a package with no web code. The Litestar names load on first use. Litestar is still installed with the package.
  • Frozen dataclasses throughout. Storage is three small protocols you implement on your database. They take and return any object with the right attributes (ClientLike, CodeLike, TokenLike), so your database layer does not import this package at runtime.

Limits

  • Public clients only. The token endpoint takes no client secret, and there is no client_credentials grant.
  • Tokens are random strings, not JWTs. A resource checks one with server.verify, so it needs the same stores. There is no introspection endpoint.
  • No OpenID Connect: no ID token and no userinfo endpoint.
  • Client ID Metadata Documents are off by default and follow a draft (version 03). See the limits on the CIMD page.
  • The SQL stores run on Postgres only, and the package ships no migrations.
  • No login page and no consent page. Your app provides both.
  • Not yet tested against Claude, ChatGPT or Cursor as clients.
  • The API can change between releases.

Contributing

Developer setup, the dev loop, and the release process live in CONTRIBUTING.md. In short: uv sync && make install-hooks, then make check runs the same gate CI runs.

License

MIT © 2026 Jorge Cardona (see LICENSE).

Metadata

Release files for litestar-oauth-server 0.0.16

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

Source distribution (sdist)

Source distribution for litestar-oauth-server 0.0.16
File Size Uploaded Provenance Actions
litestar_oauth_server-0.0.16.tar.gz 76.0 kB Without provenance Details for litestar_oauth_server-0.0.16.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for litestar-oauth-server 0.0.16
File Interpreter ABI Platform Actions
litestar_oauth_server-0.0.16-py3-none-any.whl Python 3 none any Details for litestar_oauth_server-0.0.16-py3-none-any.whl

Total release size: 128.5 kB

Release files / litestar_oauth_server-0.0.16.tar.gz

Download URL litestar_oauth_server-0.0.16.tar.gz
Size 76.0 kB
Tags Source
SHA-256 checksum
How to use checksums
63f5426e51c83afd6545844c7f2c6bdcc3cb20e737f9c47cce1800b239c006a3
BLAKE2b-256 checksum
How to use checksums
9fd8ef38df8811f1021e0f1135a182d77bc32a12c8dbbe26c9014cd179aeb72a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.11.19 {"installer":{"name":"uv","version":"0.11.19","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Debian GNU/Linux","version":"12","id":"bookworm","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / litestar_oauth_server-0.0.16-py3-none-any.whl

Download URL litestar_oauth_server-0.0.16-py3-none-any.whl
Size 52.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
9a419429f437f513e1d2d63f2cdccbd16a5cdb9cdd2a12322ec1b1794ccf558b
BLAKE2b-256 checksum
How to use checksums
40c256d5ea360ccea3ce9b57bcb47b19b38838076b795d88c2fd9b9a57a3f4e5
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.11.19 {"installer":{"name":"uv","version":"0.11.19","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Debian GNU/Linux","version":"12","id":"bookworm","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for litestar-oauth-server 0.0.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.

No provenance found

None of the files in this release were uploaded with provenance metadata.

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