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,14 @@
|
||||
# Zitadel OIDC (server-side auth)
|
||||
ZITADEL_ISSUER=http://host.docker.internal:8080
|
||||
ZITADEL_CLIENT_ID=your-web-app-client-id
|
||||
ZITADEL_CLIENT_SECRET=your-web-app-client-secret
|
||||
|
||||
# Where Zitadel redirects back after login (must be registered in the app)
|
||||
AUTH_REDIRECT_URI=http://localhost:5173/auth/callback
|
||||
AUTH_POST_LOGOUT_URI=http://localhost:5173/
|
||||
|
||||
# Secret used to sign the session cookie (any long random string)
|
||||
SESSION_SECRET=change-me-to-a-long-random-string
|
||||
|
||||
# Backend API base URL (used from later parts)
|
||||
API_BASE_URL=http://localhost:5111
|
||||
Generated
+675
-106
File diff suppressed because it is too large
Load Diff
@@ -21,5 +21,10 @@
|
||||
"tailwindcss": "^4.3.0",
|
||||
"typescript": "^6.0.3",
|
||||
"vite": "^8.0.16"
|
||||
},
|
||||
"dependencies": {
|
||||
"@sveltejs/adapter-node": "^5.5.7",
|
||||
"jose": "^6.2.3",
|
||||
"openid-client": "^6.8.4"
|
||||
}
|
||||
}
|
||||
|
||||
Vendored
+6
-1
@@ -1,9 +1,14 @@
|
||||
// See https://svelte.dev/docs/kit/types#app.d.ts
|
||||
// for information about these interfaces
|
||||
import type { SessionUser } from '$lib/types';
|
||||
|
||||
declare global {
|
||||
namespace App {
|
||||
// interface Error {}
|
||||
// interface Locals {}
|
||||
interface Locals {
|
||||
user: SessionUser | null;
|
||||
accessToken: string | null;
|
||||
}
|
||||
// interface PageData {}
|
||||
// interface PageState {}
|
||||
// interface Platform {}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import type { Handle } from '@sveltejs/kit';
|
||||
import { decodeSession, SESSION_COOKIE } from '$lib/server/auth';
|
||||
|
||||
export const handle: Handle = async ({ event, resolve }) => {
|
||||
const session = await decodeSession(event.cookies.get(SESSION_COOKIE));
|
||||
|
||||
if (session && session.expiresAt * 1000 > Date.now()) {
|
||||
event.locals.user = {
|
||||
sub: session.sub,
|
||||
name: session.name,
|
||||
email: session.email,
|
||||
picture: session.picture
|
||||
};
|
||||
event.locals.accessToken = session.accessToken;
|
||||
} else {
|
||||
event.locals.user = null;
|
||||
event.locals.accessToken = null;
|
||||
}
|
||||
|
||||
return resolve(event);
|
||||
};
|
||||
@@ -1,4 +1,12 @@
|
||||
<script lang="ts">
|
||||
import type { SessionUser } from '$lib/types';
|
||||
|
||||
interface Props {
|
||||
user: SessionUser | null;
|
||||
}
|
||||
|
||||
let { user }: Props = $props();
|
||||
|
||||
const links = [
|
||||
{ href: '/', label: 'Inicio' },
|
||||
{ href: '/explore', label: 'Explorar' }
|
||||
@@ -19,15 +27,37 @@
|
||||
</div>
|
||||
|
||||
<div class="flex items-center gap-3">
|
||||
<a href="/login" class="text-sm font-medium text-neutral-300 transition hover:text-white">
|
||||
Iniciar sesión
|
||||
</a>
|
||||
<a
|
||||
href="/login"
|
||||
class="rounded-full bg-emerald-500 px-4 py-2 text-sm font-semibold text-neutral-950 transition hover:bg-emerald-400"
|
||||
>
|
||||
Registrarse
|
||||
</a>
|
||||
{#if user}
|
||||
<a href="/explore" class="flex items-center gap-2 text-sm text-neutral-200">
|
||||
{#if user.picture}
|
||||
<img src={user.picture} alt="" class="h-7 w-7 rounded-full object-cover" />
|
||||
{:else}
|
||||
<span
|
||||
class="grid h-7 w-7 place-items-center rounded-full bg-neutral-700 text-xs font-semibold uppercase"
|
||||
>
|
||||
{(user.name ?? user.email ?? '?').charAt(0)}
|
||||
</span>
|
||||
{/if}
|
||||
<span class="hidden sm:inline">{user.name ?? user.email}</span>
|
||||
</a>
|
||||
<form method="POST" action="/logout">
|
||||
<button
|
||||
class="rounded-full border border-white/15 px-4 py-2 text-sm font-semibold text-white transition hover:bg-white/5"
|
||||
>
|
||||
Salir
|
||||
</button>
|
||||
</form>
|
||||
{:else}
|
||||
<a href="/login" class="text-sm font-medium text-neutral-300 transition hover:text-white">
|
||||
Iniciar sesión
|
||||
</a>
|
||||
<a
|
||||
href="/login?mode=register"
|
||||
class="rounded-full bg-emerald-500 px-4 py-2 text-sm font-semibold text-neutral-950 transition hover:bg-emerald-400"
|
||||
>
|
||||
Registrarse
|
||||
</a>
|
||||
{/if}
|
||||
</div>
|
||||
</nav>
|
||||
</header>
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
import * as client from 'openid-client';
|
||||
import { SignJWT, jwtVerify } from 'jose';
|
||||
import { env } from '$env/dynamic/private';
|
||||
import type { SessionUser } from '$lib/types';
|
||||
|
||||
export const SESSION_COOKIE = 'mf_session';
|
||||
export const STATE_COOKIE = 'mf_oidc_state';
|
||||
export const VERIFIER_COOKIE = 'mf_oidc_verifier';
|
||||
export const NONCE_COOKIE = 'mf_oidc_nonce';
|
||||
export const RETURN_COOKIE = 'mf_oidc_return';
|
||||
|
||||
export interface Session extends SessionUser {
|
||||
accessToken: string;
|
||||
refreshToken?: string;
|
||||
idToken?: string;
|
||||
expiresAt: number;
|
||||
}
|
||||
|
||||
export const OIDC_SCOPE = 'openid profile email offline_access';
|
||||
|
||||
let configPromise: Promise<client.Configuration> | null = null;
|
||||
|
||||
export function getOidcConfig(): Promise<client.Configuration> {
|
||||
configPromise ??= (async () => {
|
||||
const issuer = new URL(env.ZITADEL_ISSUER);
|
||||
const options =
|
||||
issuer.protocol === 'http:' ? { execute: [client.allowInsecureRequests] } : undefined;
|
||||
return client.discovery(
|
||||
issuer,
|
||||
env.ZITADEL_CLIENT_ID,
|
||||
env.ZITADEL_CLIENT_SECRET,
|
||||
undefined,
|
||||
options
|
||||
);
|
||||
})();
|
||||
return configPromise;
|
||||
}
|
||||
|
||||
export const authConfig = {
|
||||
get redirectUri() {
|
||||
return env.AUTH_REDIRECT_URI;
|
||||
},
|
||||
get postLogoutUri() {
|
||||
return env.AUTH_POST_LOGOUT_URI;
|
||||
}
|
||||
};
|
||||
|
||||
const sessionKey = () => new TextEncoder().encode(env.SESSION_SECRET);
|
||||
|
||||
export async function encodeSession(session: Session): Promise<string> {
|
||||
return new SignJWT({ ...session })
|
||||
.setProtectedHeader({ alg: 'HS256' })
|
||||
.setIssuedAt()
|
||||
.setExpirationTime('7d')
|
||||
.sign(sessionKey());
|
||||
}
|
||||
|
||||
export async function decodeSession(token: string | undefined): Promise<Session | null> {
|
||||
if (!token) return null;
|
||||
try {
|
||||
const { payload } = await jwtVerify(token, sessionKey());
|
||||
return payload as unknown as Session;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
export interface SessionUser {
|
||||
sub: string;
|
||||
name?: string;
|
||||
email?: string;
|
||||
picture?: string;
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import type { LayoutServerLoad } from './$types';
|
||||
|
||||
export const load: LayoutServerLoad = ({ locals }) => ({
|
||||
user: locals.user
|
||||
});
|
||||
@@ -4,13 +4,13 @@
|
||||
import Navbar from '$lib/components/Navbar.svelte';
|
||||
import Footer from '$lib/components/Footer.svelte';
|
||||
|
||||
let { children } = $props();
|
||||
let { children, data } = $props();
|
||||
</script>
|
||||
|
||||
<svelte:head><link rel="icon" href={favicon} /></svelte:head>
|
||||
|
||||
<div class="flex min-h-screen flex-col bg-neutral-950 text-neutral-100 antialiased">
|
||||
<Navbar />
|
||||
<Navbar user={data.user} />
|
||||
<main class="flex-1">{@render children()}</main>
|
||||
<Footer />
|
||||
</div>
|
||||
|
||||
@@ -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);
|
||||
};
|
||||
@@ -0,0 +1,50 @@
|
||||
import { redirect } from '@sveltejs/kit';
|
||||
import * as client from 'openid-client';
|
||||
import type { RequestHandler } from './$types';
|
||||
import {
|
||||
getOidcConfig,
|
||||
authConfig,
|
||||
OIDC_SCOPE,
|
||||
STATE_COOKIE,
|
||||
VERIFIER_COOKIE,
|
||||
NONCE_COOKIE,
|
||||
RETURN_COOKIE
|
||||
} from '$lib/server/auth';
|
||||
|
||||
export const GET: RequestHandler = async ({ url, cookies }) => {
|
||||
const config = await getOidcConfig();
|
||||
|
||||
const codeVerifier = client.randomPKCECodeVerifier();
|
||||
const codeChallenge = await client.calculatePKCECodeChallenge(codeVerifier);
|
||||
const state = client.randomState();
|
||||
const nonce = client.randomNonce();
|
||||
|
||||
const register = url.searchParams.get('mode') === 'register';
|
||||
const returnTo = url.searchParams.get('returnTo') ?? '/explore';
|
||||
|
||||
const parameters: Record<string, string> = {
|
||||
redirect_uri: authConfig.redirectUri,
|
||||
scope: OIDC_SCOPE,
|
||||
code_challenge: codeChallenge,
|
||||
code_challenge_method: 'S256',
|
||||
state,
|
||||
nonce
|
||||
};
|
||||
if (register) parameters.prompt = 'create';
|
||||
|
||||
const authorizationUrl = client.buildAuthorizationUrl(config, parameters);
|
||||
|
||||
const cookieOptions = {
|
||||
httpOnly: true,
|
||||
sameSite: 'lax' as const,
|
||||
secure: url.protocol === 'https:',
|
||||
path: '/',
|
||||
maxAge: 600
|
||||
};
|
||||
cookies.set(VERIFIER_COOKIE, codeVerifier, cookieOptions);
|
||||
cookies.set(STATE_COOKIE, state, cookieOptions);
|
||||
cookies.set(NONCE_COOKIE, nonce, cookieOptions);
|
||||
cookies.set(RETURN_COOKIE, returnTo, cookieOptions);
|
||||
|
||||
redirect(302, authorizationUrl.href);
|
||||
};
|
||||
@@ -0,0 +1,20 @@
|
||||
import { redirect } from '@sveltejs/kit';
|
||||
import * as client from 'openid-client';
|
||||
import type { RequestHandler } from './$types';
|
||||
import { getOidcConfig, authConfig, decodeSession, SESSION_COOKIE } from '$lib/server/auth';
|
||||
|
||||
const handleLogout: RequestHandler = async ({ cookies }) => {
|
||||
const session = await decodeSession(cookies.get(SESSION_COOKIE));
|
||||
cookies.delete(SESSION_COOKIE, { path: '/' });
|
||||
|
||||
const config = await getOidcConfig();
|
||||
const endSessionUrl = client.buildEndSessionUrl(config, {
|
||||
post_logout_redirect_uri: authConfig.postLogoutUri,
|
||||
...(session?.idToken ? { id_token_hint: session.idToken } : {})
|
||||
});
|
||||
|
||||
redirect(302, endSessionUrl.href);
|
||||
};
|
||||
|
||||
export const GET = handleLogout;
|
||||
export const POST = handleLogout;
|
||||
@@ -1,5 +1,5 @@
|
||||
import tailwindcss from '@tailwindcss/vite';
|
||||
import adapter from '@sveltejs/adapter-auto';
|
||||
import adapter from '@sveltejs/adapter-node';
|
||||
import { sveltekit } from '@sveltejs/kit/vite';
|
||||
import { defineConfig } from 'vite';
|
||||
|
||||
|
||||
Reference in New Issue
Block a user