coreapp new --sso: sign-in through the Core's Authelia

A template overlay (templates/sso) registers the app as an OpenID Connect
client in Authelia's idproviders.yml (between markers, secret hashed by
the running Authelia), checks the configuration before restarting
Authelia and restores it if the check fails; uninstall removes the client.
The app reaches Authelia's https address through traefik (@TRAEFIK_IP@,
provided by the template's install and by redeploys). The example is a
standard-library Python OIDC client (code flow with PKCE). Tested by
install, redeploy, remove and reinstall, and a real sign-in in a browser.

Also: the postgres overlay appends to the base install, uninstall and
env.in; database names get a coreapp_ prefix (PostgreSQL reserves pg_*);
deploy waits until the app answers on its own address.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-03 12:34:27 -07:00
co-authored by Claude Opus 5.5
parent 74bdc13f0f
commit 284f52fc29
19 changed files with 419 additions and 37 deletions
+1
View File
@@ -0,0 +1 @@
www
+8
View File
@@ -0,0 +1,8 @@
# The app's image. coreapp deploy builds it as coreapp/{{NAME}}:<VERSION>
# and copies it to the Core. Replace this with your own app; keep it
# listening on the port in docker-compose.yml.in (8080).
FROM python:3.13-slim
COPY app.py /app/app.py
USER nobody
EXPOSE 8080
CMD ["python", "-u", "/app/app.py"]
+21
View File
@@ -0,0 +1,21 @@
## Sign-in
People sign in with their Core account, through the Core's Authelia
(OpenID Connect, authorization code flow with PKCE):
- `install` registers the client `coreapp-{{NAME}}` in Authelia's
`idproviders.yml` (between `### coreapp-{{NAME}} begin/end` markers), with
the random `OIDC_CLIENT_SECRET` from `.env`, hashed. It checks Authelia's
configuration before restarting it and puts the old one back if the check
fails. `uninstall` removes the client.
- Its redirect URI is `https://{{NAME}}.<domain>/auth/callback`. Change it in
`install` if your app uses another path.
- Authelia decides whether a second factor is needed (the Core's 2FA policy
is applied to every client after each install).
- The app reaches `https://authelia.<domain>` through traefik
(`extra_hosts` in `docker-compose.yml.in`).
- `app.py` shows the whole flow with Python's standard library: `/login`,
`/auth/callback`, `/logout`. For a real app, use your framework's OpenID
Connect library with `OIDC_ISSUER`, `OIDC_CLIENT_ID` and
`OIDC_CLIENT_SECRET`.
+205
View File
@@ -0,0 +1,205 @@
"""{{TITLE}}: signs people in with the Core's Authelia (OpenID Connect).
Python's standard library only. Settings come from the environment (.env on
the Core): APP_URL, APP_SECRET, OIDC_ISSUER, OIDC_CLIENT_ID,
OIDC_CLIENT_SECRET.
/login sends the browser to Authelia; Authelia sends it back to
/auth/callback with a code, which the app exchanges for an access token
(authorization code flow with PKCE) and uses to ask who signed in.
"""
import base64
import hashlib
import hmac
import html
import json
import os
import secrets
import time
import urllib.error
import urllib.parse
import urllib.request
from http.cookies import SimpleCookie
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
APP_URL = os.environ["APP_URL"].rstrip("/")
APP_SECRET = os.environ["APP_SECRET"].encode()
ISSUER = os.environ["OIDC_ISSUER"].rstrip("/")
CLIENT_ID = os.environ["OIDC_CLIENT_ID"]
CLIENT_SECRET = os.environ["OIDC_CLIENT_SECRET"]
REDIRECT_URI = APP_URL + "/auth/callback"
SESSION_SECONDS = 3600
_discovery = {}
def discovery():
"""Authelia's endpoints, from its OpenID Connect discovery document."""
if not _discovery:
url = ISSUER + "/.well-known/openid-configuration"
with urllib.request.urlopen(url, timeout=10) as response:
_discovery.update(json.load(response))
return _discovery
def b64(data):
return base64.urlsafe_b64encode(data).rstrip(b"=").decode()
def unb64(text):
return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))
def sign(value):
"""A cookie value only this app can make: data.signature."""
data = b64(json.dumps(value).encode())
mac = hmac.new(APP_SECRET, data.encode(), hashlib.sha256).digest()
return data + "." + b64(mac)
def unsign(cookie):
try:
data, mac = cookie.rsplit(".", 1)
good = hmac.new(APP_SECRET, data.encode(), hashlib.sha256).digest()
if not hmac.compare_digest(unb64(mac), good):
return None
value = json.loads(unb64(data))
except (ValueError, json.JSONDecodeError):
return None
if value.get("expires", 0) < time.time():
return None
return value
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
url = urllib.parse.urlsplit(self.path)
query = dict(urllib.parse.parse_qsl(url.query))
routes = {
"/": self.home,
"/login": self.login,
"/auth/callback": self.callback,
"/logout": self.logout,
"/health": lambda q: self.reply(200, "ok\n", "text/plain"),
}
route = routes.get(url.path)
if route is None:
self.reply(404, "Not found\n", "text/plain")
return
try:
route(query)
except (urllib.error.URLError, KeyError, ValueError) as error:
self.reply(502, f"Sign-in failed: {error}\n", "text/plain")
def cookie(self, name):
cookies = SimpleCookie(self.headers.get("Cookie", ""))
return cookies[name].value if name in cookies else None
def home(self, query):
user = unsign(self.cookie("session") or "")
if user:
groups = ", ".join(user.get("groups") or []) or "none"
body = (
f"<p>Signed in as <strong id=\"user\">{html.escape(user['name'])}</strong>"
f" ({html.escape(user['email'])}), groups: {html.escape(groups)}.</p>"
'<p><a href="/logout">Sign out</a></p>'
)
else:
body = '<p><a href="/login">Sign in with your Core account</a></p>'
self.page(body)
def login(self, query):
# state ties Authelia's answer to this browser; the PKCE verifier
# proves the code is redeemed by whoever asked for it
state = secrets.token_urlsafe(24)
verifier = secrets.token_urlsafe(48)
challenge = b64(hashlib.sha256(verifier.encode()).digest())
params = {
"response_type": "code",
"client_id": CLIENT_ID,
"redirect_uri": REDIRECT_URI,
"scope": "openid profile email groups",
"state": state,
"code_challenge": challenge,
"code_challenge_method": "S256",
}
flow = sign({"state": state, "verifier": verifier, "expires": time.time() + 600})
location = discovery()["authorization_endpoint"] + "?" + urllib.parse.urlencode(params)
self.redirect(location, [("flow", flow, 600)])
def callback(self, query):
flow = unsign(self.cookie("flow") or "")
if not flow or not hmac.compare_digest(flow["state"], query.get("state", "")):
self.reply(400, "Sign-in expired or didn't start here. Try again.\n", "text/plain")
return
if "error" in query:
self.reply(400, f"Authelia said: {query.get('error_description', query['error'])}\n", "text/plain")
return
# Exchange the code for tokens (client_secret_basic)
form = urllib.parse.urlencode({
"grant_type": "authorization_code",
"code": query["code"],
"redirect_uri": REDIRECT_URI,
"code_verifier": flow["verifier"],
}).encode()
auth = base64.b64encode(
f"{urllib.parse.quote(CLIENT_ID)}:{urllib.parse.quote(CLIENT_SECRET)}".encode()
).decode()
request = urllib.request.Request(
discovery()["token_endpoint"], data=form,
headers={"Authorization": "Basic " + auth,
"Content-Type": "application/x-www-form-urlencoded"})
with urllib.request.urlopen(request, timeout=10) as response:
tokens = json.load(response)
# Who signed in
request = urllib.request.Request(
discovery()["userinfo_endpoint"],
headers={"Authorization": "Bearer " + tokens["access_token"]})
with urllib.request.urlopen(request, timeout=10) as response:
info = json.load(response)
session = sign({
"name": info.get("name") or info.get("preferred_username") or info["sub"],
"email": info.get("email", ""),
"groups": info.get("groups", []),
"expires": time.time() + SESSION_SECONDS,
})
self.redirect("/", [("session", session, SESSION_SECONDS), ("flow", "", 0)])
def logout(self, query):
self.redirect("/", [("session", "", 0)])
def page(self, body):
self.reply(200, f"""<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>{{TITLE}}</title></head>
<body>
<h1>{{TITLE}}</h1>
<p>Running on Federated Core, deployed with coreapp-dev.</p>
{body}
</body>
</html>
""", "text/html; charset=utf-8")
def redirect(self, location, cookies=()):
self.send_response(302)
self.send_header("Location", location)
for name, value, max_age in cookies:
self.send_header(
"Set-Cookie",
f"{name}={value}; Max-Age={max_age}; Path=/; Secure; HttpOnly; SameSite=Lax")
self.send_header("Content-Length", "0")
self.end_headers()
def reply(self, status, body, content_type):
data = body.encode()
self.send_response(status)
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
if __name__ == "__main__":
print("Listening on port 8080", flush=True)
ThreadingHTTPServer(("", 8080), Handler).serve_forever()
+27
View File
@@ -0,0 +1,27 @@
services:
{{NAME}}:
image: coreapp/{{NAME}}:${IMAGE_VERSION}
container_name: {{NAME}}
hostname: {{NAME}}.@DOMAIN@
restart: always
networks:
core:
ipv4_address: {{IP}}
# Reach Authelia's https address through traefik on the core network
# (inside it, authelia.@DOMAIN@ is Authelia's own plain-http container)
extra_hosts:
- "authelia.@DOMAIN@:@TRAEFIK_IP@"
env_file:
- ./.env
volumes:
- ./data:/data
labels:
- "traefik.enable=true"
- "traefik.http.routers.{{NAME}}.rule=Host(`{{NAME}}.@DOMAIN@`)"
- "traefik.http.routers.{{NAME}}.entrypoints=websecure"
- "traefik.http.routers.{{NAME}}.tls.certresolver=letsencrypt"
- "traefik.http.services.{{NAME}}.loadbalancer.server.port=8080"
networks:
core:
external: true
+5
View File
@@ -0,0 +1,5 @@
# Sign-in through the Core's Authelia (OpenID Connect); install registers
# the client
OIDC_ISSUER=https://authelia.@DOMAIN@
OIDC_CLIENT_ID=coreapp-{{NAME}}
OIDC_CLIENT_SECRET=@OIDC_CLIENT_SECRET:RANDOM:LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL@
+43
View File
@@ -0,0 +1,43 @@
# Register it with the Core's Authelia as an OpenID Connect client, with the
# secret from .env (hashed), between markers so uninstall can remove it.
# Safe to run again. Authelia is checked with the new client before it
# restarts; if the check fails, its old configuration is put back.
IDP=/federated/apps/authelia/data/config/idproviders.yml
OIDC_CLIENT_SECRET="$(sed -n 's/^OIDC_CLIENT_SECRET=//p' /federated/apps/{{NAME}}/.env)"
OIDC_HASH="$(docker exec authelia authelia crypto hash generate pbkdf2 --password "$OIDC_CLIENT_SECRET" | awk '/Digest:/ {print $2}')"
cp -p "$IDP" "$IDP.coreapp-{{NAME}}.bak"
sed -i '/^ ### coreapp-{{NAME}} begin$/,/^ ### coreapp-{{NAME}} end$/d' "$IDP"
cat >> "$IDP" <<OIDC
### coreapp-{{NAME}} begin
- client_id: 'coreapp-{{NAME}}'
client_name: '{{TITLE}}'
client_secret: '$OIDC_HASH'
consent_mode: 'implicit'
public: false
authorization_policy: 'one_factor'
require_pkce: true
pkce_challenge_method: 'S256'
redirect_uris:
- 'https://{{NAME}}.$DOMAIN/auth/callback'
scopes:
- 'openid'
- 'profile'
- 'email'
- 'groups'
response_types:
- 'code'
grant_types:
- 'authorization_code'
token_endpoint_auth_method: 'client_secret_basic'
userinfo_signed_response_alg: 'none'
### coreapp-{{NAME}} end
OIDC
if docker exec authelia authelia validate-config > /dev/null 2>&1; then
rm -f "$IDP.coreapp-{{NAME}}.bak"
restart_service authelia
else
echo "Authelia rejected the new client; left its configuration as it was." >&2
mv "$IDP.coreapp-{{NAME}}.bak" "$IDP"
fi
unset IDP OIDC_CLIENT_SECRET OIDC_HASH
+9
View File
@@ -0,0 +1,9 @@
NAME="{{TITLE}}"
DESCRIPTION="{{TITLE}}, made with coreapp-dev"
DOCS=
CONTAINER=coreapp/{{NAME}}
VERSION=0.1.0
INTERNAL_IP={{IP}}
DEPENDS="authelia"
PORTS=8080
MONITOR="https://{{NAME}}.@DOMAIN@|http_2xx"
+4
View File
@@ -0,0 +1,4 @@
# ...and its Authelia client
sed -i '/^ ### coreapp-{{NAME}} begin$/,/^ ### coreapp-{{NAME}} end$/d' \
/federated/apps/authelia/data/config/idproviders.yml
restart_service authelia