Overlays no longer replace service: each names the Core apps it needs in .depends, merged into DEPENDS. The sign-in code is a module (oidc.py) that examples import; templates/postgres-sso is the combined example (sign-in, each person's visits counted in PostgreSQL). Tested with team-visits, including sign-in in a browser. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
144 lines
4.9 KiB
Python
144 lines
4.9 KiB
Python
"""Sign-in with the Core's Authelia (OpenID Connect), standard library only.
|
|
|
|
Authorization code flow with PKCE, and a signed session cookie. Settings
|
|
come from the environment (.env on the Core): APP_URL, APP_SECRET,
|
|
OIDC_ISSUER, OIDC_CLIENT_ID, OIDC_CLIENT_SECRET.
|
|
|
|
location, flow = start_login() # /login: redirect to Authelia
|
|
user = finish_login(query, flow) # /auth/callback: who signed in
|
|
cookie = make_session(user) # keep them signed in
|
|
user = read_session(cookie) # later requests (None if not)
|
|
|
|
For a real app, your framework's OpenID Connect library does the same with
|
|
OIDC_ISSUER, OIDC_CLIENT_ID and OIDC_CLIENT_SECRET.
|
|
"""
|
|
|
|
import base64
|
|
import hashlib
|
|
import hmac
|
|
import json
|
|
import os
|
|
import secrets
|
|
import time
|
|
import urllib.parse
|
|
import urllib.request
|
|
|
|
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
|
|
FLOW_SECONDS = 600
|
|
|
|
|
|
class SignInError(Exception):
|
|
"""The sign-in didn't complete (expired, cancelled, refused)."""
|
|
|
|
|
|
_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, seconds):
|
|
"""A cookie value only this app can make (data.signature), expiring."""
|
|
value = dict(value, expires=time.time() + seconds)
|
|
data = _b64(json.dumps(value).encode())
|
|
mac = hmac.new(APP_SECRET, data.encode(), hashlib.sha256).digest()
|
|
return data + "." + _b64(mac)
|
|
|
|
|
|
def unsign(cookie):
|
|
"""The value in a cookie from sign(), or None if forged or expired."""
|
|
try:
|
|
data, mac = (cookie or "").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
|
|
return value if value.get("expires", 0) >= time.time() else None
|
|
|
|
|
|
def start_login():
|
|
"""Where to send the browser, and a cookie value to keep until it's back.
|
|
|
|
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)
|
|
params = {
|
|
"response_type": "code",
|
|
"client_id": CLIENT_ID,
|
|
"redirect_uri": REDIRECT_URI,
|
|
"scope": "openid profile email groups",
|
|
"state": state,
|
|
"code_challenge": _b64(hashlib.sha256(verifier.encode()).digest()),
|
|
"code_challenge_method": "S256",
|
|
}
|
|
location = discovery()["authorization_endpoint"] + "?" + urllib.parse.urlencode(params)
|
|
return location, sign({"state": state, "verifier": verifier}, FLOW_SECONDS)
|
|
|
|
|
|
def finish_login(query, flow_cookie):
|
|
"""Who signed in: {sub, name, email, groups}, from Authelia's answer."""
|
|
flow = unsign(flow_cookie)
|
|
if not flow or not hmac.compare_digest(flow["state"], query.get("state", "")):
|
|
raise SignInError("The sign-in expired or didn't start here. Try again.")
|
|
if "error" in query:
|
|
raise SignInError(query.get("error_description", query["error"]))
|
|
# Exchange the code for tokens (client_secret_basic)
|
|
form = urllib.parse.urlencode({
|
|
"grant_type": "authorization_code",
|
|
"code": query.get("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)
|
|
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)
|
|
return {
|
|
"sub": info["sub"],
|
|
"name": info.get("name") or info.get("preferred_username") or info["sub"],
|
|
"email": info.get("email", ""),
|
|
"groups": info.get("groups", []),
|
|
}
|
|
|
|
|
|
def make_session(user):
|
|
return sign(user, SESSION_SECONDS)
|
|
|
|
|
|
def read_session(cookie):
|
|
return unsign(cookie)
|