feat(frontend): server-side Zitadel OIDC auth (part 2)
Add Authorization Code + PKCE login/logout against Zitadel, handled entirely server-side with an httpOnly signed session cookie: - $lib/server/auth: openid-client discovery (config cached), jose-signed session encode/decode, cookie/name constants - routes: /login (builds the authorize URL with PKCE/state/nonce, ?mode=register -> prompt=create), /auth/callback (code exchange + session cookie), /logout (clears session + Zitadel end_session) - hooks.server populates locals.user/accessToken from the session - +layout.server exposes the user; Navbar shows the signed-in user + Salir, or Iniciar sesión / Registrarse - switch to adapter-node; env-driven config (.env gitignored, .env.example committed) with issuer http://host.docker.internal:8080 Verified: svelte-check + build clean; dev smoke test shows the landing in the logged-out state and /login issuing a 302 to Zitadel's authorize endpoint with PKCE/state/nonce (discovery reachable). Real client id/secret still needed to complete the token exchange.
This commit is contained in:
@@ -0,0 +1,69 @@
|
||||
import { redirect, error } from '@sveltejs/kit';
|
||||
import * as client from 'openid-client';
|
||||
import type { RequestHandler } from './$types';
|
||||
import {
|
||||
getOidcConfig,
|
||||
encodeSession,
|
||||
type Session,
|
||||
SESSION_COOKIE,
|
||||
STATE_COOKIE,
|
||||
VERIFIER_COOKIE,
|
||||
NONCE_COOKIE,
|
||||
RETURN_COOKIE
|
||||
} from '$lib/server/auth';
|
||||
|
||||
export const GET: RequestHandler = async ({ url, cookies }) => {
|
||||
const codeVerifier = cookies.get(VERIFIER_COOKIE);
|
||||
const state = cookies.get(STATE_COOKIE);
|
||||
const nonce = cookies.get(NONCE_COOKIE);
|
||||
const returnTo = cookies.get(RETURN_COOKIE) ?? '/explore';
|
||||
|
||||
if (!codeVerifier || !state) {
|
||||
error(400, 'Estado de autenticación inválido. Vuelve a iniciar sesión.');
|
||||
}
|
||||
|
||||
const config = await getOidcConfig();
|
||||
|
||||
let tokens;
|
||||
try {
|
||||
tokens = await client.authorizationCodeGrant(config, url, {
|
||||
pkceCodeVerifier: codeVerifier,
|
||||
expectedState: state,
|
||||
expectedNonce: nonce,
|
||||
idTokenExpected: true
|
||||
});
|
||||
} catch (exception) {
|
||||
console.error('Token exchange failed', exception);
|
||||
error(401, 'La autenticación ha fallado.');
|
||||
}
|
||||
|
||||
const claims = tokens.claims();
|
||||
if (!claims) {
|
||||
error(401, 'El proveedor no devolvió el token de identidad.');
|
||||
}
|
||||
|
||||
const session: Session = {
|
||||
sub: String(claims.sub),
|
||||
name: claims.name as string | undefined,
|
||||
email: claims.email as string | undefined,
|
||||
picture: claims.picture as string | undefined,
|
||||
accessToken: tokens.access_token,
|
||||
refreshToken: tokens.refresh_token,
|
||||
idToken: tokens.id_token,
|
||||
expiresAt: Math.floor(Date.now() / 1000) + (tokens.expires_in ?? 3600)
|
||||
};
|
||||
|
||||
cookies.set(SESSION_COOKIE, await encodeSession(session), {
|
||||
httpOnly: true,
|
||||
sameSite: 'lax',
|
||||
secure: url.protocol === 'https:',
|
||||
path: '/',
|
||||
maxAge: 60 * 60 * 24 * 7
|
||||
});
|
||||
|
||||
for (const name of [STATE_COOKIE, VERIFIER_COOKIE, NONCE_COOKIE, RETURN_COOKIE]) {
|
||||
cookies.delete(name, { path: '/' });
|
||||
}
|
||||
|
||||
redirect(302, returnTo);
|
||||
};
|
||||
Reference in New Issue
Block a user