# Python and Django

> Sign users in from Django, Flask, FastAPI or any Python app with the 9in packages, and protect your APIs.

Source: https://9in.io/docs/python-django/

Python apps sign users in as a **confidential client** (see [Server-rendered apps](https://9in.io/docs/server-apps/) for how that works). Use the 9in packages: [`9in-django`](https://github.com/9in-io/django) for Django, and the [Python SDK](https://github.com/9in-io/python-sdk) (`9in`, imported as `nine`) for Flask, FastAPI and everything else. Any OpenID Connect client, such as Authlib, works too.

Create the application first: **Applications → Create application → Regular Web App**, with your callback URL (for example `https://app.acme.com/nine/callback`) and logout URL (`https://app.acme.com/`), and copy the client ID and secret.

## Django

```bash
pip install 9in-django
```

```bash
NINE_ISSUER=https://acme.9in.io          # or your custom login domain
NINE_CLIENT_ID=app_…
NINE_CLIENT_SECRET=…
# NINE_AUDIENCE=https://api.acme.com     # access tokens for your own API
```

```python
# settings.py
INSTALLED_APPS = [..., "nine_django"]
MIDDLEWARE = [
    ...,
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "nine_django.middleware.NineMiddleware",     # after AuthenticationMiddleware
    ...,
]
AUTHENTICATION_BACKENDS = [
    "django.contrib.auth.backends.ModelBackend",
    "nine_django.backends.NineBackend",
]
LOGIN_URL = "nine:login"                          # @login_required sends visitors to 9in

# urls.py
path("nine/", include("nine_django.urls")),       # /nine/login, /signup, /callback, /logout, /webhook
```

Run `python manage.py migrate`, then protect pages as usual:

```python
@login_required
def dashboard(request):
    request.user          # a Django user, created or linked on first sign-in
    request.nine.claims   # the verified ID token: sub, email, name, …
```

```html
<a href="{% url 'nine:login' %}?return_to=/dashboard">Sign in</a>
<a href="{% url 'nine:signup' %}">Create an account</a>
<a href="{% url 'nine:logout' %}">Sign out</a>
```

Each 9in user is linked to a local user the first time they sign in: an existing user with the same verified email, or a new one. The middleware refreshes the tokens before they expire (refresh tokens rotate), and signs the user out when 9in ends the session (signed out everywhere, session revoked, user blocked or deleted). `request.nine.access_token()` gives a fresh access token for your API. `python manage.py check` warns about a missing backend, the wrong middleware order, an insecure issuer and signed-cookie sessions.

Protect an API with `@require_token`. Tokens must be issued for `NINE_API_AUDIENCE`, which defaults to `NINE_AUDIENCE`:

```python
from nine_django.decorators import require_token

@require_token(scope="orders:read")
def orders(request):
    request.nine.claims   # sub, client_id, scope, aud, …
```

With the client ID and secret set, tokens are verified in **hybrid** mode: a local check, then one cached introspection in the Django cache. `/nine/webhook` drops cached answers when it receives `token.revoked`, `session.revoked` or `user.*` events; set `NINE_WEBHOOK_SECRET` and subscribe that URL in the console. For Django REST framework (`pip install "9in-django[drf]"`), use `nine_django.rest_framework.NineTokenAuthentication` and `HasScope("orders:read")`.

Webhooks become Django signals, once per event:

```python
from django.dispatch import receiver
from nine_django.signals import user_created

@receiver(user_created)
def add_contact(sender, data, **kwargs):
    crm.add(data["user"]["email"])
```

To keep users in your own database, add `path("nine/", include("nine_django.adapter.urls"))` and set `NINE_ADAPTER_SECRET`. It serves the [adapter](https://9in.io/docs/own-database/) endpoints from your user model: passwords are checked with `check_password()`, inactive users are blocked, and one-time codes are emailed with `send_mail`. `python manage.py nine_login_link jane@acme.com` prints a single-use [sign-in link](https://9in.io/docs/login-links/).

## Flask

```bash
pip install "9in[flask]"
```

```bash
NINE_ISSUER=https://acme.9in.io
NINE_CLIENT_ID=app_…
NINE_CLIENT_SECRET=…
NINE_REDIRECT_URI=https://app.acme.com/nine/callback
```

```python
from flask import Flask
from nine.flask import create_blueprint, current_user, get_access_token, login_required

app = Flask(__name__)
app.secret_key = "…"
app.register_blueprint(create_blueprint())   # /nine/login, /nine/signup, /nine/callback, /nine/logout

@app.get("/dashboard")
@login_required                              # signed-out visitors sign in and come back
def dashboard():
    user = current_user()                    # sub, email, name, … from the verified ID token
    token = get_access_token()               # refreshed (and rotated) when it expires
    return f"Hello {user['email']}"
```

Link to `/nine/login?return_to=/dashboard` (or `/nine/signup`) and `/nine/logout`, which revokes the refresh token and ends the 9in session. Flask's default session is a signed cookie the user can read: use a server-side session (Flask-Session) to keep tokens off the browser.

## Any Python framework

`WebAppAuth` runs the flow; you keep the pending login and the tokens in your server-side session:

```python
import nine

auth = nine.WebAppAuth.from_env()   # NINE_ISSUER, NINE_CLIENT_ID, NINE_CLIENT_SECRET, NINE_REDIRECT_URI

# GET /nine/login
login = auth.create_login(return_to="/dashboard")      # screen="signup" for the sign-up form
session["nine_login"] = login.pending
# redirect to login.url

# GET /nine/callback: checks state, iss and PKCE, verifies the ID token
tokens = auth.handle_callback(request_url, session.pop("nine_login", None))
session["nine_tokens"] = tokens.to_dict()               # tokens.claims: sub, email, name, …

# later: refresh tokens rotate, so save the new set
tokens = auth.ensure_fresh(nine.TokenSet.from_dict(session["nine_tokens"]))

# GET /nine/logout
auth.revoke(tokens.refresh_token)
logout_url = auth.logout_url(id_token_hint=tokens.id_token, post_logout_redirect_uri="https://app.acme.com/")
```

## Protect an API in Python

```python
from nine import HybridTokenVerifier

verifier = HybridTokenVerifier(
    "https://acme.9in.io",
    audience="https://api.acme.com",
    client_id=client_id, client_secret=client_secret,   # hybrid: one cached introspection per token
)
claims = verifier.verify(request.headers.get("Authorization"), scope="orders:read")   # 401 / 403 errors
```

Without client credentials it verifies locally only (`TokenVerifier` does the same). In Flask, use `@require_auth(scope="orders:read")` from `nine.flask`; in FastAPI, `Depends(require_auth(scope="orders:read"))` from `nine.fastapi`. Pass your webhook events to `verifier.handle_event(event)` so revocations apply at once.

The same package has `ManagementClient`, `verify_webhook` with `EventDeduplicator`, and an `AdapterHandler` for [your own database](https://9in.io/docs/own-database/). Every class reads `NINE_*` settings with `from_env()`. It needs Python 3.10 or later and has one dependency (`cryptography`).
