feat(idp): add keycloak-first support with authentik fallback
This commit is contained in:
@@ -136,12 +136,12 @@ def _generate_api_key() -> str:
|
||||
def _sync_member_to_authentik(
|
||||
*,
|
||||
user_sub: str | None,
|
||||
idp_user_id: int | None,
|
||||
idp_user_id: str | None,
|
||||
username: str | None,
|
||||
email: str | None,
|
||||
display_name: str | None,
|
||||
is_active: bool,
|
||||
) -> dict[str, str | int]:
|
||||
) -> dict[str, str]:
|
||||
if not email:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="email_required_for_authentik_sync")
|
||||
settings = get_settings()
|
||||
@@ -602,7 +602,7 @@ def upsert_member(
|
||||
display_name=payload.display_name,
|
||||
is_active=payload.is_active,
|
||||
)
|
||||
idp_user_id = int(sync["idp_user_id"])
|
||||
idp_user_id = str(sync["idp_user_id"])
|
||||
if sync.get("user_sub"):
|
||||
resolved_sub = str(sync["user_sub"])
|
||||
if not resolved_sub:
|
||||
@@ -651,7 +651,7 @@ def update_member(
|
||||
display_name=next_display_name,
|
||||
is_active=next_is_active,
|
||||
)
|
||||
idp_user_id = int(sync["idp_user_id"])
|
||||
idp_user_id = str(sync["idp_user_id"])
|
||||
|
||||
row = users_repo.upsert_by_sub(
|
||||
user_sub=row.user_sub,
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import logging
|
||||
import secrets
|
||||
from urllib.parse import urljoin
|
||||
|
||||
import httpx
|
||||
from fastapi import APIRouter, HTTPException, status
|
||||
@@ -18,6 +17,9 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _resolve_username_by_email(settings, email: str) -> str | None:
|
||||
# Authentik-only helper. Keycloak does not need this path.
|
||||
if settings.use_keycloak:
|
||||
return None
|
||||
if not settings.authentik_base_url or not settings.authentik_admin_token:
|
||||
return None
|
||||
|
||||
@@ -51,19 +53,17 @@ def _resolve_username_by_email(settings, email: str) -> str | None:
|
||||
@router.post("/login", response_model=LoginResponse)
|
||||
def login(payload: LoginRequest) -> LoginResponse:
|
||||
settings = get_settings()
|
||||
client_id = settings.authentik_client_id or settings.authentik_audience
|
||||
client_id = settings.idp_client_id or settings.idp_audience
|
||||
|
||||
if not settings.authentik_base_url or not client_id or not settings.authentik_client_secret:
|
||||
if not settings.idp_base_url or not client_id or not settings.idp_client_secret:
|
||||
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail="authentik_login_not_configured")
|
||||
|
||||
token_endpoint = settings.authentik_token_endpoint or urljoin(
|
||||
settings.authentik_base_url.rstrip("/") + "/", "application/o/token/"
|
||||
)
|
||||
token_endpoint = settings.idp_token_endpoint
|
||||
|
||||
form = {
|
||||
"grant_type": "password",
|
||||
"client_id": client_id,
|
||||
"client_secret": settings.authentik_client_secret,
|
||||
"client_secret": settings.idp_client_secret,
|
||||
"username": payload.username,
|
||||
"password": payload.password,
|
||||
"scope": "openid profile email",
|
||||
@@ -74,7 +74,7 @@ def login(payload: LoginRequest) -> LoginResponse:
|
||||
token_endpoint,
|
||||
data=form_data,
|
||||
timeout=10,
|
||||
verify=settings.authentik_verify_tls,
|
||||
verify=settings.idp_verify_tls,
|
||||
headers={"Content-Type": "application/x-www-form-urlencoded"},
|
||||
)
|
||||
return resp
|
||||
@@ -95,7 +95,7 @@ def login(payload: LoginRequest) -> LoginResponse:
|
||||
raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail="authentik_unreachable") from exc
|
||||
|
||||
if resp.status_code >= 400:
|
||||
logger.warning("authentik password grant failed: status=%s body=%s", resp.status_code, resp.text)
|
||||
logger.warning("idp password grant failed: status=%s body=%s", resp.status_code, resp.text)
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="invalid_username_or_password")
|
||||
|
||||
data = resp.json()
|
||||
@@ -116,13 +116,14 @@ def get_oidc_authorize_url(
|
||||
redirect_uri: str,
|
||||
login_hint: str | None = None,
|
||||
prompt: str = "login",
|
||||
idp_hint: str | None = None,
|
||||
) -> OIDCAuthUrlResponse:
|
||||
settings = get_settings()
|
||||
client_id = settings.authentik_client_id or settings.authentik_audience
|
||||
if not settings.authentik_base_url or not client_id:
|
||||
client_id = settings.idp_client_id or settings.idp_audience
|
||||
if not settings.idp_base_url or not client_id:
|
||||
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail="authentik_login_not_configured")
|
||||
|
||||
authorize_endpoint = urljoin(settings.authentik_base_url.rstrip("/") + "/", "application/o/authorize/")
|
||||
authorize_endpoint = settings.idp_authorize_endpoint
|
||||
state = secrets.token_urlsafe(24)
|
||||
query = {
|
||||
"client_id": client_id,
|
||||
@@ -134,6 +135,8 @@ def get_oidc_authorize_url(
|
||||
}
|
||||
if login_hint:
|
||||
query["login_hint"] = login_hint
|
||||
if idp_hint and settings.use_keycloak:
|
||||
query["kc_idp_hint"] = idp_hint
|
||||
|
||||
params = httpx.QueryParams(query)
|
||||
return OIDCAuthUrlResponse(authorize_url=f"{authorize_endpoint}?{params}")
|
||||
@@ -142,17 +145,15 @@ def get_oidc_authorize_url(
|
||||
@router.post("/oidc/exchange", response_model=LoginResponse)
|
||||
def exchange_oidc_code(payload: OIDCCodeExchangeRequest) -> LoginResponse:
|
||||
settings = get_settings()
|
||||
client_id = settings.authentik_client_id or settings.authentik_audience
|
||||
if not settings.authentik_base_url or not client_id or not settings.authentik_client_secret:
|
||||
client_id = settings.idp_client_id or settings.idp_audience
|
||||
if not settings.idp_base_url or not client_id or not settings.idp_client_secret:
|
||||
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail="authentik_login_not_configured")
|
||||
|
||||
token_endpoint = settings.authentik_token_endpoint or urljoin(
|
||||
settings.authentik_base_url.rstrip("/") + "/", "application/o/token/"
|
||||
)
|
||||
token_endpoint = settings.idp_token_endpoint
|
||||
form = {
|
||||
"grant_type": "authorization_code",
|
||||
"client_id": client_id,
|
||||
"client_secret": settings.authentik_client_secret,
|
||||
"client_secret": settings.idp_client_secret,
|
||||
"code": payload.code,
|
||||
"redirect_uri": payload.redirect_uri,
|
||||
}
|
||||
@@ -162,14 +163,14 @@ def exchange_oidc_code(payload: OIDCCodeExchangeRequest) -> LoginResponse:
|
||||
token_endpoint,
|
||||
data=form,
|
||||
timeout=10,
|
||||
verify=settings.authentik_verify_tls,
|
||||
verify=settings.idp_verify_tls,
|
||||
headers={"Content-Type": "application/x-www-form-urlencoded"},
|
||||
)
|
||||
except Exception as exc:
|
||||
raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail="authentik_unreachable") from exc
|
||||
|
||||
if resp.status_code >= 400:
|
||||
logger.warning("authentik auth-code exchange failed: status=%s body=%s", resp.status_code, resp.text)
|
||||
logger.warning("idp auth-code exchange failed: status=%s body=%s", resp.status_code, resp.text)
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="authentik_code_exchange_failed")
|
||||
|
||||
data = resp.json()
|
||||
|
||||
@@ -57,6 +57,8 @@ def get_permission_snapshot(
|
||||
|
||||
|
||||
@router.post("/authentik/users/ensure", response_model=AuthentikEnsureUserResponse)
|
||||
@router.post("/idp/users/ensure", response_model=AuthentikEnsureUserResponse)
|
||||
@router.post("/keycloak/users/ensure", response_model=AuthentikEnsureUserResponse)
|
||||
def ensure_authentik_user(
|
||||
payload: AuthentikEnsureUserRequest,
|
||||
db: Session = Depends(get_db),
|
||||
|
||||
Reference in New Issue
Block a user