Metadata-Version: 2.4
Name: nextidp
Version: 0.2.0
Summary: Sign-in for Python web apps, and OAuth for APIs, MCP servers and services: sessions, access token checks, protected resource metadata, token exchange and service tokens, for FastAPI, Flask and the MCP SDK.
Keywords: oauth,openid-connect,oidc,sign-in,mcp,flask,fastapi,authentication
Author: sajanv88
License-Expression: MIT
License-File: LICENSE
Classifier: Development Status :: 3 - Alpha
Classifier: Framework :: FastAPI
Classifier: Framework :: Flask
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3.15
Classifier: Topic :: Internet :: WWW/HTTP
Classifier: Topic :: Security
Classifier: Typing :: Typed
Requires-Dist: anyio>=4.16
Requires-Dist: cryptography>=50.0.2
Requires-Dist: httpx>=0.28.1
Requires-Dist: joserfc>=1.8
Requires-Dist: fastapi>=0.164 ; extra == 'fastapi'
Requires-Dist: flask>=3.1.3 ; extra == 'flask'
Requires-Dist: mcp>=2.3,<3 ; extra == 'mcp'
Requires-Python: >=3.11
Project-URL: Homepage, https://sajanv88.github.io/next-identity-server/
Project-URL: Repository, https://github.com/sajanv88/next-identity-server
Project-URL: Issues, https://github.com/sajanv88/next-identity-server/issues
Project-URL: Changelog, https://github.com/sajanv88/next-identity-server/blob/main/packages/nextidp-py/CHANGELOG.md
Provides-Extra: fastapi
Provides-Extra: flask
Provides-Extra: mcp
Description-Content-Type: text/markdown

# nextidp for Python

Sign-in for Python web apps, and OAuth for APIs, MCP servers and services, against [Next-Identity Server](https://github.com/sajanv88/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](https://www.npmjs.com/package/nextidp), and the two share their cookie and store format, so a Python app and a Node app can share sessions.

```sh
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

```python
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

```python
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

```python
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

```python
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

```python
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

```python
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

```python
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.

```python
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 `datetime`s. 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

```sh
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
