Metadata-Version: 2.4
Name: kik-oidc
Version: 0.2.0
Summary: Reusable Django OIDC authentication app using Authlib
Author: Wichert Akkerman
Author-email: Wichert Akkerman <wichert@wiggy.net>
License-Expression: EUPL-1.2
Requires-Dist: authlib>=1.9.5
Requires-Dist: django>=4.2,<5.3
Requires-Dist: kik-os[django]
Requires-Dist: requests
Requires-Python: >=3.12
Description-Content-Type: text/markdown

# kik-oidc

OpenID Connect (OIDC) authentication for Kik-OS Django projects. kik-oidc
uses [Authlib](https://authlib.org/) for the authorization-code flow and
provides login, callback and logout views, user provisioning, and session
token refresh.

## Requirements

- Python 3.12 or later
- Django 4.2 or later, before 5.3
- Kik-OS with its Django components
- An OIDC provider that supports discovery, ID tokens and UserInfo

Install the package in your Django project's environment:

```console
uv add kik-oidc
```

## Django configuration

Add `kik_oidc` to `INSTALLED_APPS`. Its application config registers the
Authlib client named `oidc`.

Configure the client using your provider's issuer, client ID and client
secret. Load secrets from your deployment's secret store rather than
committing them to settings.

<!-- markdownlint-capture -->
<!-- markdownlint-disable line-length -->
```python
import os

INSTALLED_APPS = [
    # Your existing applications...
    "kik_oidc",
]

OIDC_HTTP_TIMEOUT = 10
OIDC_RP_SCOPES = "openid email profile"

AUTHLIB_OAUTH_CLIENTS = {
    "oidc": {
        "client_id": os.environ["OIDC_CLIENT_ID"],
        "client_secret": os.environ["OIDC_CLIENT_SECRET"],
        "server_metadata_url": (
            os.environ["OIDC_ISSUER"].rstrip("/")
            + "/.well-known/openid-configuration"
        ),
        "client_kwargs": {
            "scope": OIDC_RP_SCOPES,
            "default_timeout": OIDC_HTTP_TIMEOUT,
        },
    },
}

AUTHENTICATION_BACKENDS = [
    "kik_oidc.auth.SsoAuthenticationBackend",
    # Optional: retain local authentication for administrators.
    "django.contrib.auth.backends.ModelBackend",
]

MIDDLEWARE.insert(
    MIDDLEWARE.index(
        "django.contrib.auth.middleware.AuthenticationMiddleware"
    ) + 1,
    "kik_oidc.middleware.OidcSessionMiddleware",
)

LOGIN_URL = "/oidc/login"
LOGIN_REDIRECT_URL = "/"

# A stable, secret key used to encrypt OIDC tokens in the database.
KIK_OS_SECRET_KEY = os.environ["KIK_OS_SECRET_KEY"]
```
<!-- markdownlint-restore -->

`OidcSessionMiddleware` must come after `AuthenticationMiddleware`. Do not
remove `SessionMiddleware` or Django's session authentication machinery:
OIDC credentials are tied to Django sessions.

To enable PKCE with S256, add the following to `client_kwargs`:

```python
"code_challenge_method": "S256",
```

Use PKCE only when your provider supports it.

### URLs

Include the OIDC URLs and use the package's logout view. The following
example keeps local login and logout available when OIDC is disabled:

```python
from django.conf import settings
from django.contrib.auth import views as auth_views
from django.urls import include, path

from kik_oidc.views import logout

urlpatterns = [
    path("login/", auth_views.LoginView.as_view(), name="login"),
    path("logout/", logout, name="logout"),
    path("oidc/", include("kik_oidc.urls")),
    # Your existing URLs...
]
```

When OIDC is the only authentication method, use
`kik_oidc.views.login` for `/login/` as well, or set `LOGIN_URL` to
`/oidc/login` as shown above. Mounting the URLs at `/oidc/` provides:

| URL | Purpose |
| --- | --- |
| `/oidc/login` | Start the authorization-code flow |
| `/oidc/callback` | Handle the provider callback |
| `/oidc/logged-out` | Local post-logout page |

Register these callback URLs with the provider, using the public origin of
your application:

```text
https://app.example.org/oidc/callback
https://app.example.org/oidc/logged-out
```

The callback URI is generated with `request.build_absolute_uri()`. Configure
Django's host and proxy settings correctly when running behind a reverse
proxy, including `ALLOWED_HOSTS`, `SECURE_PROXY_SSL_HEADER` and HTTPS
redirects as appropriate.

Log out with a POST request, for example:

```html
<form method="post" action="{% url 'logout' %}">
  {% csrf_token %}
  <button type="submit">Sign out</button>
</form>
```

GET requests to the OIDC logout view are rejected. If the provider supports
end-session, logout includes an `id_token_hint` and a post-logout redirect.

## Provider claims

The requested scopes must produce a verified ID token containing `iss` and
`sub`, and a UserInfo response whose `sub` matches the ID token. The
`organization` claim is required in UserInfo.

The standard `openid email profile` scopes normally provide the identity
claims below. Configure your provider to add `organization` as a custom
UserInfo claim; it is not supplied by all providers by default.

| Claim | Use |
| --- | --- |
| `iss`, `sub` | Stable OIDC identity |
| `organization` | Kik-OS hub slug |
| `email` | User email address |
| `given_name`, `family_name` | User first and last name |
| `name` | SSO profile full name |

A user is identified by the unique `(iss, sub)` pair, not by username or
email address. New users receive an unusable password and a deterministic
OIDC username derived from the issuer and subject. Returning users have
non-empty changed profile claims updated.

## Hubs and memberships

`organization` must be a valid lowercase hub slug. The user must be active,
the hub must be active, and the user must be an accepted member.

With Kik-OS schema tenancy (`KIK_TENANCY = "schemas"`), a missing valid hub
is created and provisioned, and the user receives an ordinary accepted
membership. Existing membership roles and states are preserved. Ambiguous
schema names and reserved slugs are rejected.

With single-hub tenancy (`KIK_TENANCY = "single"`), the hub must already
exist. An unknown organization is rejected rather than creating a hub.

Do not use the first OIDC login as the only way to grant administrative
access: newly provisioned users receive ordinary memberships.

## Sessions and token storage

The session middleware checks OIDC credentials on authenticated requests
and refreshes tokens shortly before access-token expiry. Refresh and ID
tokens are encrypted in the database; access tokens are not persisted.
Sessions still expire at their normal Django expiry, even if the provider
allows longer-lived refresh tokens.

Keep `KIK_OS_SECRET_KEY` stable and secret. Losing all configured decryption
keys makes stored tokens unusable. A project can instead set
`KIK_OS_SECRET_BOX` to a dotted path for a Kik-OS-compatible encryption
module.

Paths beginning with `/oidc/` or `/logout/` are excluded from session
refresh checks by default. Set `OIDC_PUBLIC_PATHS` to override this tuple.
If your Kik-OS project uses sign-in gating or schema-aware hub middleware,
also allow the OIDC endpoints through those layers, for example:

```python
KIK_EXTRA_OPEN_PATHS = ("/oidc",)
KIK_CENTRAL_PATHS = ("/oidc/", "/logout/")
```

Use a scheduled call to `kik_oidc.sessions.cleanup()` if you want to remove
credentials associated with expired Django sessions.

## Development

Run the test suite and linter with:

```console
uv run --frozen pytest
uv run ruff check tests
```

The test suite uses SQLite and mocked provider responses; no external OIDC
provider is needed.

Releases are managed with Release Please. Merging its release pull request
creates a GitHub release and publishes the package to PyPI through trusted
publishing.
