feat: SSO-Login per OpenID Connect (Authentik u.a.)
Dritte Login-Methode neben Passwort und Passkey, konfiguriert über OIDC_ISSUER/OIDC_CLIENT_ID/OIDC_CLIENT_SECRET (optional, Button bleibt ohne diese Vars ausgeblendet). Authorization-Code-Flow mit PKCE, ID-Token-Signaturprüfung gegen das JWKS des Providers via neuer Abhängigkeit "jose" (RS256 fest gepinnt gegen Algorithm-Confusion), State/Nonce kurzlebig und einmalig verwendbar in neuer Tabelle oidc_states (Migration 0003, analog zu webauthn_challenges). Funktioniert ausschließlich für bereits angelegte Benutzer (Abgleich per E-Mail) – kein Auto-Provisioning, keine Rollenübernahme aus Claims, beides bleibt exklusiv über die bestehende Benutzerverwaltung steuerbar. app/login/page.tsx zu Server-Component-Wrapper reduziert (prüft isConfigured(), liest ?error= aus searchParams), bisheriger Inhalt nach components/LoginForm.tsx verschoben. Version 1.9.0. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,60 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { queryOne } from "@/lib/db";
|
||||
import { createSession } from "@/lib/auth/session";
|
||||
import { isConfigured } from "@/lib/auth/oidc-config";
|
||||
import { consumeState } from "@/lib/auth/oidc-state";
|
||||
import { discover, exchangeCode, resolveEmail, verifyIdToken } from "@/lib/auth/oidc-client";
|
||||
import type { Role } from "@/lib/types";
|
||||
|
||||
function errorRedirect(request: Request, code: string): NextResponse {
|
||||
return NextResponse.redirect(new URL(`/login?error=${code}`, request.url));
|
||||
}
|
||||
|
||||
// GET statt POST: der Identity Provider leitet den Browser per
|
||||
// Redirect hierher (Cross-Origin-Navigation) – die übliche
|
||||
// isSameOrigin()-CSRF-Prüfung greift hier nicht und wird bewusst nicht
|
||||
// verwendet. Die Absicherung ist der einmalig verwendbare state-
|
||||
// Parameter (Standard-OIDC-Mechanismus, siehe lib/auth/oidc-state.ts).
|
||||
export async function GET(request: Request) {
|
||||
if (!isConfigured()) {
|
||||
return errorRedirect(request, "oidc_failed");
|
||||
}
|
||||
|
||||
const url = new URL(request.url);
|
||||
const code = url.searchParams.get("code");
|
||||
const state = url.searchParams.get("state");
|
||||
const idpError = url.searchParams.get("error");
|
||||
if (idpError || !code || !state) {
|
||||
return errorRedirect(request, "oidc_failed");
|
||||
}
|
||||
|
||||
const stored = await consumeState(state);
|
||||
if (!stored) {
|
||||
return errorRedirect(request, "oidc_invalid_state");
|
||||
}
|
||||
|
||||
try {
|
||||
const discovery = await discover();
|
||||
const { idToken, accessToken } = await exchangeCode(discovery, code, stored.codeVerifier);
|
||||
const payload = await verifyIdToken(discovery, idToken, stored.nonce);
|
||||
const email = await resolveEmail(discovery, payload, accessToken);
|
||||
if (!email) {
|
||||
return errorRedirect(request, "oidc_failed");
|
||||
}
|
||||
|
||||
const user = await queryOne<{ id: string; role: Role }>(
|
||||
"select id, role from users where email = $1",
|
||||
[email.trim().toLowerCase()]
|
||||
);
|
||||
if (!user) {
|
||||
return errorRedirect(request, "oidc_unknown_user");
|
||||
}
|
||||
|
||||
await createSession(user.id);
|
||||
return NextResponse.redirect(
|
||||
new URL(user.role === "admin" ? "/admin" : "/intern", request.url)
|
||||
);
|
||||
} catch {
|
||||
return errorRedirect(request, "oidc_failed");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { createHash, randomBytes } from "node:crypto";
|
||||
import { NextResponse } from "next/server";
|
||||
import { isConfigured } from "@/lib/auth/oidc-config";
|
||||
import { storeState } from "@/lib/auth/oidc-state";
|
||||
import { buildAuthorizeUrl, discover } from "@/lib/auth/oidc-client";
|
||||
|
||||
// Bewusst ein einfacher GET-Link statt eines CSRF-gesicherten POSTs:
|
||||
// der Browser muss hier auf die fremde Login-Seite des Identity
|
||||
// Providers navigieren (funktioniert nicht per fetch/XHR) – identisch
|
||||
// zum Muster jeder "Login mit X"-Schaltfläche. Die Absicherung gegen
|
||||
// Cross-Site-Missbrauch übernimmt der state-Parameter im Callback.
|
||||
export async function GET(request: Request) {
|
||||
if (!isConfigured()) {
|
||||
return NextResponse.json({ error: "oidc_not_configured" }, { status: 404 });
|
||||
}
|
||||
|
||||
const state = randomBytes(32).toString("base64url");
|
||||
const nonce = randomBytes(32).toString("base64url");
|
||||
const codeVerifier = randomBytes(32).toString("base64url");
|
||||
const codeChallenge = createHash("sha256").update(codeVerifier).digest("base64url");
|
||||
|
||||
try {
|
||||
const discovery = await discover();
|
||||
await storeState(state, nonce, codeVerifier);
|
||||
return NextResponse.redirect(
|
||||
buildAuthorizeUrl(discovery, { state, nonce, codeChallenge })
|
||||
);
|
||||
} catch {
|
||||
return NextResponse.redirect(new URL("/login?error=oidc_failed", request.url));
|
||||
}
|
||||
}
|
||||
+9
-143
@@ -1,145 +1,11 @@
|
||||
"use client";
|
||||
import LoginForm from "@/components/LoginForm";
|
||||
import { isConfigured } from "@/lib/auth/oidc-config";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import Link from "next/link";
|
||||
import { startAuthentication } from "@simplewebauthn/browser";
|
||||
import { formatMessage } from "@/lib/i18n/shared";
|
||||
import { useDict } from "@/components/i18n/LocaleProvider";
|
||||
import LanguageSwitcher from "@/components/i18n/LanguageSwitcher";
|
||||
import type { Dict } from "@/lib/i18n/shared";
|
||||
|
||||
function authErrorMessage(dict: Dict, code: string): string {
|
||||
if (code === "invalid_credentials") return dict.login.errorInvalidCredentials;
|
||||
if (code === "password_disabled") return dict.login.errorPasswordDisabled;
|
||||
if (/cancelled|aborted|NotAllowedError/i.test(code))
|
||||
return dict.login.errorPasskeyCancelled;
|
||||
return formatMessage(dict.login.errorGeneric, { message: code });
|
||||
}
|
||||
|
||||
function redirectPath(role: string): string {
|
||||
return role === "admin" ? "/admin" : "/intern";
|
||||
}
|
||||
|
||||
export default function LoginPage() {
|
||||
const router = useRouter();
|
||||
const dict = useDict();
|
||||
const [email, setEmail] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
async function signInWithPassword(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
setBusy(true);
|
||||
const res = await fetch("/api/auth/login", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ email, password }),
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) {
|
||||
setError(authErrorMessage(dict, data.error ?? "unknown"));
|
||||
setBusy(false);
|
||||
return;
|
||||
}
|
||||
router.replace(redirectPath(data.role));
|
||||
router.refresh();
|
||||
}
|
||||
|
||||
async function signInWithPasskey() {
|
||||
setError(null);
|
||||
setBusy(true);
|
||||
try {
|
||||
const optionsRes = await fetch("/api/auth/passkeys/login-options", { method: "POST" });
|
||||
const options = await optionsRes.json();
|
||||
const response = await startAuthentication({ optionsJSON: options });
|
||||
|
||||
const verifyRes = await fetch("/api/auth/passkeys/login-verify", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ response }),
|
||||
});
|
||||
const data = await verifyRes.json().catch(() => ({}));
|
||||
if (!verifyRes.ok) {
|
||||
setError(authErrorMessage(dict, data.error ?? "unknown"));
|
||||
setBusy(false);
|
||||
return;
|
||||
}
|
||||
router.replace(redirectPath(data.role));
|
||||
router.refresh();
|
||||
} catch (err) {
|
||||
setError(authErrorMessage(dict, err instanceof Error ? err.message : String(err)));
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex-1 flex items-center justify-center p-4">
|
||||
<div className="card w-full max-w-sm">
|
||||
<div className="flex justify-between items-center mb-4">
|
||||
<h1 className="text-xl font-bold text-[var(--c-primary)]">
|
||||
{dict.login.title}
|
||||
</h1>
|
||||
<LanguageSwitcher variant="light" />
|
||||
</div>
|
||||
<form onSubmit={signInWithPassword} className="space-y-3">
|
||||
<div>
|
||||
<label className="label" htmlFor="email">
|
||||
{dict.common.email}
|
||||
</label>
|
||||
<input
|
||||
id="email"
|
||||
type="email"
|
||||
className="input"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
autoComplete="username webauthn"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="label" htmlFor="password">
|
||||
{dict.common.password}
|
||||
</label>
|
||||
<input
|
||||
id="password"
|
||||
type="password"
|
||||
className="input"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
autoComplete="current-password"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
{error && <p className="text-sm text-[var(--c-del)]">{error}</p>}
|
||||
<button type="submit" className="btn btn-primary w-full" disabled={busy}>
|
||||
{dict.login.submit}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<div className="my-4 flex items-center gap-3 text-xs text-gray-400">
|
||||
<span className="h-px flex-1 bg-gray-200" />
|
||||
{dict.login.or}
|
||||
<span className="h-px flex-1 bg-gray-200" />
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={signInWithPasskey}
|
||||
className="btn btn-neutral w-full"
|
||||
disabled={busy}
|
||||
>
|
||||
{dict.login.passkeyButton}
|
||||
</button>
|
||||
|
||||
<p className="mt-4 text-center text-sm">
|
||||
<Link href="/" className="text-gray-500 hover:text-[var(--c-primary)]">
|
||||
{dict.login.backToMenu}
|
||||
</Link>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
export default async function LoginPage({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<{ error?: string }>;
|
||||
}) {
|
||||
const { error } = await searchParams;
|
||||
return <LoginForm oidcEnabled={isConfigured()} initialError={error ?? null} />;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user