Skip to main content

nextidp for Python

Sign-in for Python web apps, and OAuth for APIs, MCP servers and services, against Next-Identity Server or any OpenID provider:

  • Sign-in with the authorization code flow and PKCE. The session lives in an encrypted cookie, or in a store such as Redis. Tokens are refreshed before they expire, and sign-out can end the session at the auth server too.
  • Access token checks. A JWT is checked against the issuer's keys and an opaque token by introspection, then its scopes, with RFC 6750's 401 and 403 challenges.
  • Protected resource metadata (RFC 9728), so MCP clients find the auth server on their own.
  • Token exchange (RFC 8693), so an MCP server calls the next API as the person instead of passing their token on.
  • Service tokens (client credentials), with an httpx auth that sends them to your API only.

It comes with adapters for FastAPI, Flask and the MCP Python SDK. The same features are in nextidp on npm, and the two share their cookie and store format, so a Python app and a Node app can share sessions.

pip install "nextidp[fastapi]"   # or [flask], [mcp]

Python 3.11 or newer. nextidp.Idp is synchronous, for Flask and other WSGI apps. nextidp.aio.Idp is the same API for asyncio.

Signing people in

Register the app on the auth server with the redirect URI <app_url>/auth/callback, then:

FastAPI

from typing import Annotated

from fastapi import Depends, FastAPI
from nextidp import Session
from nextidp.fastapi import Idp

idp = Idp(app_url="https://app.example.com")  # IDP_ISSUER, IDP_CLIENT_ID, IDP_SECRET
app = FastAPI(lifespan=idp.lifespan)
idp.install(app, sign_in=True)


@app.get("/me")
async def me(session: Annotated[Session, Depends(idp.require_session)]):
    return {"name": session.user.name}

Flask

from flask import Flask
from nextidp.flask import Idp, current_session, require_session

app = Flask(__name__)
Idp(app, sign_in=True, app_url="https://app.example.com")


@app.get("/me")
@require_session
def me():
    return {"name": current_session().user.name}

With sign_in=True, nextidp answers its routes under /auth:

  • GET /auth/login?returnTo=/somewhere starts a sign-in. idp.sign_in_path("/somewhere") builds the link.
  • GET /auth/callback finishes it.
  • POST /auth/logout signs out. A form field signOutOfIdp=true also signs out of the auth server.
  • POST /auth/refresh refreshes the session.

Every other request gets its session read, and refreshed when its access token is about to expire. A signed-out GET to a route that requires a session is sent to sign in; any other request gets a 401. A failed sign-in lands on error_path with ?error=access_denied, expired, state_mismatch, token_failed, invalid_id_token or refresh_failed.

session.access_token calls APIs as the person; the refresh token never leaves nextidp. Other frameworks can use idp.handle(WebRequest(...)) for the routes, and idp.refresh_if_needed(cookie_header) for each request's session.

Sessions in a store

import redis.asyncio
from nextidp.aio import RedisStore
from nextidp.fastapi import Idp

idp = Idp(app_url="https://app.example.com", store=RedisStore(redis.asyncio.Redis()))

With a store, the cookie holds only a sealed reference, and the store holds the session, encrypted too. Sign-out ends the session even for a copy of the old cookie. Every instance of the app shares the sessions, and so does an app on the npm package with the same client ID. With nextidp.Idp, pass RedisStore(redis.Redis()); MemoryStore() is for one process.

A store also turns on back-channel logout. Register <app_url>/auth/backchannel-logout as the client's back-channel logout URI, and when the auth server ends a session, the app's sessions from it end too.

APIs

FastAPI

from typing import Annotated

from fastapi import FastAPI, Security
from nextidp import AccessToken
from nextidp.fastapi import Idp

idp = Idp(audience="https://api.example.com")  # issuer from IDP_ISSUER
app = FastAPI(lifespan=idp.lifespan)
idp.install(app)


@app.get("/orders")
async def orders(
    token: Annotated[AccessToken, Security(idp.require_token, scopes=["orders:read"])],
):
    return list_orders(token.subject)

Every Security(idp.require_token, scopes=[...]) checks its own scopes, so a router's dependencies and a route's parameter are both enforced. A refused token gets a 401 or 403 with its WWW-Authenticate challenge. install gives the response RFC 6750's JSON body and serves the metadata. A token that can't be checked right now, for example while the auth server is down, gets a 503, never a pass.

Flask

from flask import Flask
from nextidp.flask import Idp, current_token, require_token

app = Flask(__name__)
Idp(app, audience="https://api.example.com")


@app.get("/orders")
@require_token(scopes=["orders:read"])
def orders():
    return list_orders(current_token().subject)

MCP servers

from mcp.server.auth.middleware.auth_context import get_access_token
from mcp.server.mcpserver import MCPServer
from nextidp import ResourceMetadata
from nextidp.aio import Idp
from nextidp.mcp import TokenVerifier, auth_settings

idp = Idp(
    audience="https://mcp.example.com/mcp",
    resource_metadata=ResourceMetadata(scopes=["orders:read"]),
)
server = MCPServer(
    "Orders",
    token_verifier=TokenVerifier(idp),
    auth=auth_settings(idp, required_scopes=["orders:read"]),
)


@server.tool()
async def list_orders() -> list[dict]:
    caller = get_access_token()  # the token the MCP client sent
    token = await idp.exchange_token(caller.token, resource="https://orders.example.com")
    ...  # call the orders API with `token`, never `caller.token`

The SDK answers a caller without a token with a 401 naming the metadata, and serves the metadata itself. With FastAPI or Flask instead of the SDK's server, set resource_metadata and the adapters do both.

Calling other APIs

import httpx
from nextidp.aio import Idp

idp = Idp()  # IDP_ISSUER, IDP_CLIENT_ID, IDP_CLIENT_SECRET, IDP_RESOURCE

token = await idp.service_token(scopes=["orders:read"])

async with httpx.AsyncClient(auth=idp.service_token_auth(scopes=["orders:read"])) as client:
    await client.get("https://orders.example.com/orders")

Tokens are kept until a minute before they expire, and calls made at the same time share one request. service_token_auth sends the token only to origins, by default the origin of resource. When the API answers 401, it asks for a new token and sends the request once more. exchange_token(subject_token, resource=...) keeps each exchanged token for no longer than the token it came from.

Managing accounts (Next-Identity Server)

nextidp.management is a service's side of Next-Identity Server's management API, for a product whose operators manage accounts from its own screens. It's that server's own API, on only with MANAGEMENT_API=true there. A lookup answers at once; a sign-out, a disable or an enable waits for an admin's approval, so what comes back is a request to check on.

The service needs a confidential client with the management API and its scopes (management:users.read to look up, management:users.manage to ask and check), and runs on the server, with the client secret in its settings.

from datetime import UTC, datetime

from nextidp.aio import Management  # nextidp.management.Management without asyncio

async with Management() as accounts:  # IDP_ISSUER, IDP_CLIENT_ID, IDP_CLIENT_SECRET
    user = await accounts.find_user(email="ada@example.com")  # or user_id=; None if none
    request = await accounts.disable(
        user.id, until=datetime(2027, 1, 31, tzinfo=UTC), reason="Chargeback"
    )
    # request.status == "pending": store request.id

    later = await accounts.request(request.id)
    # approved (done), denied (later.note), expired, failed (later.problem) or pending

    page = await accounts.requests(since=last_check)  # decided since then, newest first
Method Scope Returns
find_user(email=), find_user(user_id=) read ManagedUser, or None
sign_out(user_id) manage A ManagedRequest: sign out everywhere
disable(user_id, until=, reason=) manage A ManagedRequest: disable, until an aware datetime within a year or until enabled
enable(user_id) manage A ManagedRequest: enable again
request(request_id) manage The ManagedRequest as it stands now, or None
requests(status=, user_id=, since=, page=) manage ManagedRequestPage: requests, page, page_count, total; 50 a page

Dates are aware datetimes. A refusal raises nextidp.management.ManagementError (an IdpError with the code management_refused), whose refusal is the API's code: admin_account, not_disabled, disabled_by_admin, too_many_pending, insufficient_scope, invalid_token or invalid_request. No answer at all is management_unavailable. Pass an Idp you already have (Management(idp)) to share its tokens and settings, and url= to point at another address than <issuer>/api/auth/management.

Settings

Every setting is a keyword argument, or else an environment variable. They're checked on first use, and a misconfigured error names everything that's wrong.

Option Variable
issuer IDP_ISSUER The auth server, https://auth.example.com. Plain http is allowed only on this machine, unless allow_http (IDP_ALLOW_HTTP=true).
client_id, client_secret IDP_CLIENT_ID, IDP_CLIENT_SECRET The client registered on the auth server. A public client has no secret.
app_url IDP_APP_URL Sign-in: this app's origin, https://app.example.com.
secret IDP_SECRET Sign-in: 32 characters or more, encrypting the cookies. A list (comma-separated) rotates it: the first encrypts, any of them decrypts.
scopes IDP_SCOPES Sign-in: default openid profile email offline_access.
base_path, after_sign_in, after_sign_out, error_path Sign-in: where the routes live (/auth), and where people land (/).
sign_out_of_idp, reauthenticate_after_sign_out, userinfo Sign-in: sign out of the auth server too by default; ask for the password again after a sign-out; read the email, name and picture from userinfo.
pushed_authorization Sign-in: push each sign-in's parameters first (RFC 9126): True, False (default) or "auto".
session_max_age, cookie_prefix, on_error Sign-in: the session's lifetime (7 days), the cookie names (nextidp), and a function told about each failure (default: a log line).
audience IDP_AUDIENCE APIs: this API's URI, exactly as the auth server lists it. Every token must name it.
resource IDP_RESOURCE The API that tokens are asked for. Never used as audience.
resource_metadata IDP_RESOURCE_METADATA APIs: True or ResourceMetadata(scopes, name) publishes the metadata at /.well-known/oauth-protected-resource plus the audience's path.
accept_own_tokens APIs: also accept an opaque token issued to this client that doesn't name audience.

Errors

Everything raises nextidp.IdpError, whose code says why. error.is_token_error marks missing_token, invalid_token and insufficient_scope, the three you answer a caller with, and token_refusal(error) gives the status, headers and body. Messages never hold a token, a secret or a claim.

Development

uv sync
uv run ruff check && uv run ruff format --check
uv run mypy
uv run pytest
uv run python scripts/generate_sync.py   # after changing src/nextidp/_async

src/nextidp/_sync is generated from src/nextidp/_async by unasync. Don't edit it; a test fails when it's out of date.

License

MIT

Metadata

Release files for nextidp 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 nextidp 0.2.0
File Size Uploaded Provenance Actions
nextidp-0.2.0.tar.gz 106.9 kB With provenance Details for nextidp-0.2.0.tar.gz

Built distribution (wheel)

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

Total release size: 202.5 kB

Release files / nextidp-0.2.0.tar.gz

Download URL nextidp-0.2.0.tar.gz
Size 106.9 kB
Tags Source
SHA-256 checksum
How to use checksums
16a432d2d651bc2617977895769cc194d73cb079b51bb1c80eed2952786084e3
BLAKE2b-256 checksum
How to use checksums
549156be287fbb845cabb7125037f9172c561a6f85b7ccf796353499742984b8
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 Dec 4, 2026.

Transparency log

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

Download URL nextidp-0.2.0-py3-none-any.whl
Size 95.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
9f6ebc924ce37a6ce40ad2e07dadeda7f4d4d6a6b348ad16b2a691d83cf1200b
BLAKE2b-256 checksum
How to use checksums
61e894552c3513f8b07b2652fb9ca6e7a50155f32f0a7cbe9cc09ee2507a2615
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 Dec 4, 2026.

Transparency log

Security for nextidp 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 nextidp-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 Dec 4, 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