Metadata-Version: 2.4
Name: auth0-server-python
Version: 1.0.0b15
Summary: Auth0 server-side Python SDK
License: MIT
License-File: LICENSE
Author: Auth0
Author-email: support@okta.com
Requires-Python: >=3.9
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Requires-Dist: authlib (>=1.2,<2.0)
Requires-Dist: cryptography (>=43.0.1)
Requires-Dist: httpx (>=0.28.1,<0.29.0)
Requires-Dist: jwcrypto (>=1.5.7,<2.0.0)
Requires-Dist: pydantic (>=2.10.6,<3.0.0)
Requires-Dist: pyjwt (>=2.8.0)
Description-Content-Type: text/markdown

The Auth0 Server Python SDK is a library for implementing user authentication in Python applications.

![PyPI](https://img.shields.io/pypi/v/auth0-server-python)
![Downloads](https://img.shields.io/pypi/dw/auth0-server-python)
[![License](https://img.shields.io/:license-MIT-blue.svg?style=flat)](https://opensource.org/licenses/MIT)
[![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/auth0/auth0-server-python)

📚 [Documentation](#documentation) - 🚀 [Getting Started](#getting-started) - 💬 [Feedback](#feedback)

## Documentation

- [Examples](https://github.com/auth0/auth0-server-python/blob/main/examples) - examples for your different use cases.
- [Docs Site](https://auth0.com/docs) - explore our docs site and learn more about Auth0.

## Getting Started

### 1. Install the SDK

```shell
pip install auth0-server-python
```

If you’re using Poetry:

```shell
poetry add auth0-server-python
```

### 2. Create the Auth0 SDK client

Create an instance of the Auth0 client. This instance will be imported and used in anywhere we need access to the authentication methods.


```python
from auth0_server_python.auth_server.server_client import ServerClient

auth0 = ServerClient(
    domain='<AUTH0_DOMAIN>',
    client_id='<AUTH0_CLIENT_ID>',
    client_secret='<AUTH0_CLIENT_SECRET>',
    secret='<AUTH0_SECRET>',
    authorization_params= {
      'redirect_uri': '<AUTH0_REDIRECT_URI>',
    }
)
```

The `AUTH0_DOMAIN`, `AUTH0_CLIENT_ID`, and `AUTH0_CLIENT_SECRET` can be obtained from the [Auth0 Dashboard](https://manage.auth0.com) once you've created an application. **This application must be a `Regular Web Application`**.

The `AUTH0_REDIRECT_URI` tells Auth0 what URL to use while redirecting the user back after successful authentication, e.g. `http://localhost:3000/auth/callback`. Note: your application needs to handle this endpoint and call the SDK's `complete_interactive_login(url: string)` to finish the authentication process. See below for more information.

The `AUTH0_SECRET` is the key used to encrypt the session and transaction cookies. You can generate a secret using `openssl`:

```shell
openssl rand -hex 64
```

#### Authenticating with Private Key JWT

The SDK authenticates to Auth0 with either a client secret or a Private Key JWT (`private_key_jwt`). To use Private Key JWT, pass your private signing key as `client_assertion_signing_key` instead of `client_secret`:

```python
from auth0_server_python.auth_server.server_client import ServerClient

with open('private_key.pem') as f:
    private_key = f.read()

auth0 = ServerClient(
    domain='<AUTH0_DOMAIN>',
    client_id='<AUTH0_CLIENT_ID>',
    client_assertion_signing_key=private_key,
    secret='<AUTH0_SECRET>',
    authorization_params={
        'redirect_uri': '<AUTH0_REDIRECT_URI>',
    }
)
```

The key must be a PKCS8 PEM private key. Register its public key on your Auth0 application under **Settings → Credentials**, and set the application's authentication method to Private Key JWT. The signing algorithm defaults to `RS256` and can be overridden with `client_assertion_signing_alg`. Auth0 accepts `RS256`, `RS384`, and `PS256`, all of which use an RSA key. The algorithm must match the key type and the algorithm chosen when the public key credential was created.

> [!NOTE]
> The passkey challenge endpoints (`register` and `challenge`) accept only a client secret, so a client configured with just a signing key cannot use them.

> [!IMPORTANT]
> Private keys must not be committed to source control. Load them from a secure secret store or an environment-provided file.

### 3. Add login to your Application (interactive)

Before using redirect-based login, ensure the `redirect_uri` is configured when initializing the SDK:

```python
auth0 = ServerClient(
    # ...
    redirect_uri='<AUTH0_REDIRECT_URI>',
    # ...
)
```

> [!IMPORTANT]  
> You will need to register the `AUTH0_REDIRECT_URI` in your Auth0 Application as an **Allowed Callback URLs** via the [Auth0 Dashboard](https://manage.auth0.com).

In order to add login to any application, call `start_interactive_login()`, and redirect the user to the returned URL.

The implementation will vary based on the framework being used, but here is an example of what this would look like in FastAPI:

```python
from fastapi import FastAPI, Request, Response
from starlette.responses import RedirectResponse

app = FastAPI()


@app.get("/auth/login")
async def login(request: Request):
    authorization_url = await auth0.start_interactive_login()
    return RedirectResponse(url=authorization_url)
```

Once the user has successfully authenticated, Auth0 will redirect the user back to the provided `redirect_uri` which needs to be handled in the application.

This implementation will also vary based on the framework used, but what needs to happen is:

- register an endpoint that will handle the configured `redirect_uri`.
- call the SDK's `complete_interactive_login(url)`, passing it the full URL, including query parameters.

Here is an example of what this would look like in FastAPI, with `redirect_uri` configured as `http://localhost:3000/auth/callback`:

```python
@app.get("/auth/callback")
async def callback(request: Request):
    result = await auth0.complete_interactive_login(str(request.url))
    # Store session or set cookies as needed
    return RedirectResponse(url="/")
```

#### Organizations

The SDK supports [Auth0 Organizations](https://auth0.com/docs/organizations) with first-class `organization` and `invitation` parameters on `ServerClient` and `StartInteractiveLoginOptions`. Token claim validation is enforced automatically at callback. For setup, invitation flows, error handling, and reading org data from the session, see [examples/InteractiveLogin.md](examples/InteractiveLogin.md#8-organizations).

### 4. Login with Custom Token Exchange

If you're migrating from a legacy authentication system or integrating with a custom identity provider, you can exchange external tokens for Auth0 tokens using the OAuth 2.0 Token Exchange specification (RFC 8693):

```python
from auth0_server_python.auth_types import LoginWithCustomTokenExchangeOptions

# Exchange a custom token and establish a session
result = await auth0.login_with_custom_token_exchange(
    LoginWithCustomTokenExchangeOptions(
        subject_token="your-custom-token",
        subject_token_type="urn:acme:mcp-token",
        audience="https://api.example.com"
    ),
    store_options={"request": request, "response": response}
)

# Access the user session
user = result.state_data["user"]
```

For advanced token exchange scenarios (without creating a session), use `custom_token_exchange()` directly:

```python
from auth0_server_python.auth_types import CustomTokenExchangeOptions

# Exchange a custom token for Auth0 tokens
response = await auth0.custom_token_exchange(
    CustomTokenExchangeOptions(
        subject_token="your-custom-token",
        subject_token_type="urn:acme:mcp-token",
        audience="https://api.example.com",
        scope="read:data write:data"
    )
)

print(response.access_token)
```

Building on token exchange, the SDK also supports:

- **[Delegation and Impersonation](examples/CustomTokenExchange.md#3-actor-tokens-delegation)** - exchange with an `actor_token` so the issued tokens record who is acting on whose behalf (the `act` claim).
- **[Impersonation via Session Transfer (STT)](examples/CustomTokenExchange.md#8-impersonation-via-session-transfer-stt)** - mint a Session Transfer Token to log an agent into a target app as a customer, via `request_session_transfer_token()` and `build_session_transfer_redirect()`.

For more details and examples, see [examples/CustomTokenExchange.md](examples/CustomTokenExchange.md).

### 5. Multiple Custom Domains (MCD)

For applications that use multiple custom domains on the same Auth0 tenant, pass a domain resolver function instead of a static domain string:

```python
from auth0_server_python.auth_server.server_client import ServerClient
from auth0_server_python.auth_types import DomainResolverContext

async def domain_resolver(context: DomainResolverContext) -> str:
    host = context.request_headers.get('host', '').split(':')[0]
    domain_map = {
        "acme.yourapp.com": "acme.auth0.com",
        "globex.yourapp.com": "globex.auth0.com",
    }
    return domain_map.get(host, "default.auth0.com")

auth0 = ServerClient(
    domain=domain_resolver,  # Callable enables MCD mode
    client_id='<AUTH0_CLIENT_ID>',
    client_secret='<AUTH0_CLIENT_SECRET>',
    secret='<AUTH0_SECRET>',
)
```

The SDK handles per-domain OIDC discovery, JWKS fetching, issuer validation, and session isolation automatically. Static string domains continue to work unchanged.

For more details and examples, see [examples/MultipleCustomDomains.md](examples/MultipleCustomDomains.md).

### 6. Session Expiry from the Upstream IdP

For enterprise connections, the upstream identity provider can cap how long a user's session lives. When the connection is configured to honor it, Auth0 includes a `session_expiry` claim in the ID token, and the SDK enforces this ceiling on every session read. Once it is reached, `get_user()` and `get_session()` return `None`, and `get_access_token()` raises an `AccessTokenError` with code `session_expired`. If the asserted ceiling is already in the past at login, `complete_interactive_login()` raises a `SessionExpiredError` instead of persisting an already-expired session.

For more details and examples, see [examples/RetrievingData.md](examples/RetrievingData.md#session-expiry-from-the-upstream-idp).

### 7. Passkey Authentication

Sign users up or in with [WebAuthn](https://www.w3.org/TR/webauthn-2/) passkeys (Touch ID, Face ID, Windows Hello, or a security key) instead of a password, via [Auth0 passkeys](https://auth0.com/docs/authenticate/database-connections/passkeys). The ceremony is two steps — request a challenge, sign it in the browser, then complete sign-in — and establishes a server-side session like every other login path. For the signup and login flows, organizations, step-up MFA, and error handling, see [examples/Passkeys.md](examples/Passkeys.md).

### 8. My Account API — Authentication Methods

Let a logged-in user manage their own enrolled authentication methods — enroll a new passkey (or other factor), list, rename, and delete — via the [My Account API](https://auth0.com/docs/manage-users/my-account-api). For obtaining a scoped token, the enroll/verify ceremony, listing, updating, deleting, and error handling, see [examples/MyAccountAuthenticationMethods.md](examples/MyAccountAuthenticationMethods.md).

### 9. DPoP — Sender-Constrained Tokens (Passkeys & MyAccount)

Bind tokens to a key your server holds ([RFC 9449](https://www.rfc-editor.org/rfc/rfc9449)) so a stolen token alone cannot be replayed. DPoP is supported for Passkey sign-in (`signin_with_passkey`) and the authentication-methods/factors methods on `MyAccountClient`. For key generation and usage, see [examples/Passkeys.md](examples/Passkeys.md#3-dpop-bound-passkey-tokens-optional) and [examples/MyAccountAuthenticationMethods.md](examples/MyAccountAuthenticationMethods.md#dpop).

### 10. Passwordless Authentication

Sign users in with a one-time code sent by email or SMS, or with a magic link sent by email, via [Auth0 embedded passwordless login](https://auth0.com/docs/authenticate/passwordless/implement-login/embedded-login/relevant-api-endpoints). OTP verification and the magic-link callback each establish a server-side session like every other login path. For prerequisites, both flows, custom scopes/audiences, step-up MFA, and error handling, see [examples/Passwordless.md](examples/Passwordless.md).

## Feedback

### Contributing

We appreciate feedback and contribution to this repo! Before you get started, please read the following:

- [Auth0's general contribution guidelines](https://github.com/auth0/open-source-template/blob/master/GENERAL-CONTRIBUTING.md)
- [Auth0's code of conduct guidelines](https://github.com/auth0/open-source-template/blob/master/CODE-OF-CONDUCT.md)
- [This repo's contribution guide](./CONTRIBUTING.md)

### Raise an issue

To provide feedback or report a bug, please [raise an issue on our issue tracker](https://github.com/auth0/auth0-server-python/issues).

## Vulnerability Reporting

Please do not report security vulnerabilities on the public GitHub issue tracker. The [Responsible Disclosure Program](https://auth0.com/responsible-disclosure-policy) details the procedure for disclosing security issues.

## What is Auth0?

<p align="center">
  <picture>
    <source media="(prefers-color-scheme: dark)" srcset="https://cdn.auth0.com/website/sdks/logos/auth0_dark_mode.png" width="150">
    <source media="(prefers-color-scheme: light)" srcset="https://cdn.auth0.com/website/sdks/logos/auth0_light_mode.png" width="150">
    <img alt="Auth0 Logo" src="https://cdn.auth0.com/website/sdks/logos/auth0_light_mode.png" width="150">
  </picture>
</p>
<p align="center">
  Auth0 is an easy to implement, adaptable authentication and authorization platform. To learn more checkout <a href="https://auth0.com/why-auth0">Why Auth0?</a>
</p>
<p align="center">
  This project is licensed under the MIT license. See the <a href="https://github.com/auth0/auth0-server-python/blob/main/LICENSE"> LICENSE</a> file for more info.
</p>

