<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Hernán Cussi on Medium]]></title>
        <description><![CDATA[Stories by Hernán Cussi on Medium]]></description>
        <link>https://medium.com/@hernncussi?source=rss-82e8d590697f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*B27hLAXWpHUjo-sI.</url>
            <title>Stories by Hernán Cussi on Medium</title>
            <link>https://medium.com/@hernncussi?source=rss-82e8d590697f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 05:45:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hernncussi/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Making a Stolen OAuth Token Useless: DPoP in Practice]]></title>
            <link>https://medium.com/@hernncussi/making-a-stolen-oauth-token-useless-dpop-in-practice-b7f3b8d85fa9?source=rss-82e8d590697f------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7f3b8d85fa9</guid>
            <category><![CDATA[spring-security]]></category>
            <category><![CDATA[keycloak]]></category>
            <category><![CDATA[dpop]]></category>
            <category><![CDATA[nextauth]]></category>
            <category><![CDATA[oauth2]]></category>
            <dc:creator><![CDATA[Hernán Cussi]]></dc:creator>
            <pubDate>Tue, 28 Jul 2026 23:04:30 GMT</pubDate>
            <atom:updated>2026-07-28T23:08:39.326Z</atom:updated>
            <content:encoded><![CDATA[<h4>Sender-constrained access tokens with Keycloak, Spring Boot, and Next.js.</h4><h4><strong>Part 4 of the Next.js + Spring Boot + Keycloak series.</strong></h4><p>In the <a href="https://medium.com/@hernncussi/step-up-authentication-with-keycloak-spring-boot-and-next-js-9f4237009100">Part 3</a> we taught one login to yield two assurance levels: a base session for <em>/hello</em>, and a TOTP-elevated <em>acr=pro</em> session for <em>/server-details</em>. The <strong>login got smarter</strong>. The <strong>token did not</strong>. It was still a <strong>bearer</strong> token, and bearer means exactly what it says: whoever bears it, uses it.</p><p>That is the quiet problem underneath every OAuth demo. Copy the <em>Authorization</em> header out of a log line, a leaked error report, a compromised proxy, and you can replay it against the backend until it expires. Step-up decides <strong>how hard</strong> it was to mint the token. It does nothing about what happens <strong>after</strong> the token exists. This article closes that gap with <strong>DPoP</strong> (Demonstrating Proof-of-Possession at the Application Layer, [<a href="https://datatracker.ietf.org/doc/html/rfc9449">RFC 9449</a>]): the token stops being something you <strong>hold</strong> and becomes something you must <strong>prove you own</strong>, on every single request.</p><h4>The Big Picture</h4><p>DPoP adds one asymmetric key pair and one extra header. The frontend generates an ES256 key, and on every call it signs a short-lived <strong>proof JWT</strong> with the private key. Keycloak stamps the public key’s thumbprint into the access token as a <em>cnf.jkt</em> (“confirmation, JWK thumbprint”) claim. The backend then refuses any request whose proof was not signed by the key the token is bound to.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vSiVjCm3-o6B-RMEzzeEig.png" /></figure><p>The scheme changes too. <em>Authorization: Bearer &lt;token&gt;</em> becomes <em>Authorization: DPoP &lt;token&gt;</em>, and a <em>DPoP: &lt;proof-jwt&gt;</em> header rides along on every request. A stolen token, on its own, is now inert: without the private key, you cannot mint the proof that matches its <em>cnf.jkt</em>.</p><h4>The Vocabulary: proof, cnf.jkt, and ath</h4><p>Three terms carry the whole design, and it is worth pinning them down before any code.</p><p>A <strong>DPoP proof</strong> is a tiny JWT, signed by the private key, that says “I am making <strong>this</strong> request <strong>right now</strong>.” Its header carries <em>typ: dpop+jwt</em> and the full public JWK; its body carries <em>htm</em> (the HTTP method), <em>htu</em> (the HTTP URI), <em>iat</em> (issued-at, for freshness), and <em>jti</em> (a unique id, for replay detection). It lives for seconds and is thrown away.<br>The <strong><em>cnf.jkt</em></strong> claim is the binding. When Keycloak issues the access token, it hashes the public JWK from the proof and writes that thumbprint into the token as <em>cnf.jkt</em>. From then on the token and the key are married: the token names the key that is allowed to speak for it.<br>The <strong><em>ath</em></strong> claim (access-token hash) is the piece that stops a proof from being reused across endpoints. On every <strong>resource</strong> call the proof adds <em>ath = base64url(https://medium.com/SHA-256(access%20token))</em>, so a proof is valid only for the exact token it was minted alongside. The token-endpoint proof omits <em>ath</em> (there is no access token yet); every backend proof includes it.</p><p>Put together: the token proves <strong>who you are</strong> (the JWT claims), and the proof proves <strong>you still hold the key the token was bound to</strong> (the signature over <em>htm</em>/<em>htu</em>/<em>ath</em>). Both must pass, on every request.</p><h4>Keycloak: require DPoP-bound tokens</h4><p>On the <strong>26.6</strong> image this stack uses, enabling DPoP is a single per-client capability toggle, “Require DPoP bound tokens”, which surfaces in the realm export as one attribute on the <em>nextjs-frontend</em> client:</p><pre>&quot;attributes&quot;: {<br>  &quot;dpop.bound.access.tokens&quot;: &quot;true&quot;<br>}</pre><p>That is the entire Keycloak change. The client stays <strong>confidential</strong> (its secret never reaches the browser, exactly as before), <strong>PKCE</strong> stays on, and the <strong>step-up</strong> flow is untouched. Once the toggle is set, the token endpoint refuses any token request that does not arrive with a valid DPoP proof, and every access token it issues for this client carries a <em>cnf.jkt</em>.</p><h4>The confidential-client nuance that is easy to assume wrong</h4><p>There is one detail here that is easy to guess wrong. For a <strong>confidential</strong> client, Keycloak 26.6 binds only the <strong>access token</strong> to the key. The refresh token is protected by the client secret instead, so it is not <em>cnf</em>-bound. But, and this is the counterintuitive part, the token endpoint <strong>still requires a DPoP proof on the <em>refresh_token</em> grant</strong>, because the <strong>new</strong> access token it mints needs to be bound to the same key. Forget the proof on refresh and your 5-minute session dies silently mid-use. In this stack the refresh path signs a proof on every renewal, and an e2e test asserts that <em>cnf.jkt</em> stays stable across the refresh cycle.</p><h4>Spring Boot: validate the proof, and refuse the downgrade</h4><p>The backend is where the sender-constraint is actually enforced, and Spring Security 7 does more of the work than you might expect. The moment <em>DPoPProofJwtDecoderFactory</em> is on the classpath, the resource server <strong>auto-enables</strong> DPoP: it accepts the <strong>DPoP</strong> scheme, checks the proof (signature, <em>htm</em>/<em>htu</em>, <em>iat</em> freshness, <em>jti</em> replay via a built-in cache, <em>ath</em>, and the <em>cnf.jkt</em> thumbprint match), and, crucially, decodes the access token through the <strong>same</strong> JWT authentication manager. That last point is what keeps iterations 1 and 2 alive: the issuer, audience, and <em>acr</em> step-up checks all still run for a DPoP-scheme request.</p><p>So the <a href="https://github.com/hcussi/nextjs-springboot-keycloak-poc/blob/main/backend/src/main/java/com/poc/backend/config/SecurityConfig.java">SecurityConfig</a> reads almost like the step-up version. The endpoint rules and the <em>acr</em> step-up handler are unchanged; the DPoP wiring is <strong>implicit</strong>:</p><pre>http<br>    .authorizeHttpRequests(auth -&gt; auth<br>        .requestMatchers(&quot;/server-details&quot;).hasAuthority(stepUpAuthority)<br>        .anyRequest().authenticated())<br>    .oauth2ResourceServer(oauth2 -&gt; oauth2<br>        .jwt(jwt -&gt; jwt.jwtAuthenticationConverter(acrAuthenticationConverter()))<br>        .accessDeniedHandler(new StepUpAccessDeniedHandler(requiredAcr, stepUpAuthority, debug)));</pre><p>Note what is <strong>not</strong> here: there is no <strong>.dpop()</strong> call to switch DPoP on. It is on because the factory is on the classpath. That leaves two ways an attacker might try to skip the proof, and this project closes both: a bound token sent as plain <em>Authorization: Bearer</em> to sidestep the proof check, and a token that has no <em>cnf.jkt</em> at all, so there is no proof to demand.</p><h4>The one guarantee the framework does not give you for free</h4><p>Sender-constraining is only real if a <em>cnf</em>-bound token <strong>cannot</strong> be used as a plain bearer token. Half of that is handled for you: Spring’s own <em>BearerTokenAuthenticationFilter</em> already rejects a <em>cnf</em>-bound token presented under the <em>Bearer</em> scheme (RFC 9449). Good. But that only covers a <strong>bound</strong> token under the wrong scheme.</p><p>The other half is the one to worry about: a token that <strong>lacks</strong> <em>cnf.jkt</em> entirely. If a misconfigured client sharing the same audience mints an unbound token, or if someone flips the Keycloak toggle off, that token would sail through the ordinary bearer path with full access, silently reopening the exact downgrade DPoP exists to prevent. So the resource server <a href="https://github.com/hcussi/nextjs-springboot-keycloak-poc/blob/main/backend/src/main/java/com/poc/backend/config/DpopBoundTokenValidator.java#L50">checks it itself</a>, in a tiny validator wired into the decoder alongside the audience check:</p><pre>Object cnf = token.getClaim(&quot;cnf&quot;);<br>if (cnf instanceof Map&lt;?, ?&gt; confirmation<br>        &amp;&amp; confirmation.get(&quot;jkt&quot;) instanceof String thumbprint<br>        &amp;&amp; !thumbprint.isBlank()) {<br>    return OAuth2TokenValidatorResult.success();<br>}<br>return OAuth2TokenValidatorResult.failure(MISSING_CNF);</pre><p>Now every accepted token must carry <em>cnf.jkt</em>, under <strong>any</strong> scheme. The two guards are complementary: the framework refuses a bound token under <em>Bearer</em>, and this validator refuses an unbound token under anything. The guarantee no longer rests on the IdP configuration alone. This one validator is the difference between “DPoP is on” and “DPoP cannot be turned off from the outside.”</p><p>The <em>jti</em> replay cache matters just as much and is worth confirming rather than assuming. Without a server-side cache keyed on <em>jti</em> + <em>cnf.jkt</em> within a tight <em>iat</em> window, an observed token <strong>and</strong> its proof could be replayed verbatim, which downgrades the whole property from “needs the key” to “needs one captured request.” Spring Security 7 ships this cache; the <a href="https://github.com/hcussi/nextjs-springboot-keycloak-poc/blob/main/scripts/e2e-login.mjs#L221">tests replay</a> a proof with the same <em>jti</em> twice and assert the second call gets a <em>401</em>.</p><h4>Next.js: the key that must never leave the server</h4><p>Here is the design decision the entire frontend hangs on, and it is subtler than “generate a key in the browser.”<br>The confidential client exchanges the authorization code for tokens <strong>server-side</strong>, inside <em>next-auth</em>, so the secret never reaches the browser. That means the thing that signs the <strong>token-endpoint</strong> proof is the Next.js server. And because the <strong>same key</strong> must sign the <strong>resource-endpoint</strong> proof (the backend checks both against one <em>cnf.jkt</em>), the key has to live server-side too. A browser-held WebCrypto key would force us to abandon the confidential client and move token handling into the browser, which is a step backwards. So the token and the key both stay in the Next.js tier, and the browser reaches the backend only through a same-origin <strong>BFF proxy</strong>.</p><p>This is a net security <strong>improvement</strong>: the browser now holds neither the access token nor the key. But it creates two problems worth naming.</p><h4>1. Where do you store a raw private key across a stateless session?</h4><p><em>next-auth v4</em> uses a stateless, encrypted (JWE), <em>httpOnly</em> session cookie. You <strong>could</strong> stuff the raw private JWK into that cookie, and it would be encrypted, but the key would round-trip the browser and its safety would rest entirely on <em>NEXTAUTH_SECRET</em>. Instead, the private key stays a Node key object in a <strong>server-side in-memory store</strong>, and only an <a href="https://github.com/hcussi/nextjs-springboot-keycloak-poc/blob/main/frontend/src/lib/dpopKeyStore.ts#L30"><strong>opaque reference</strong></a> (a random id) goes into the cookie:</p><pre>export function putDpopKey(key: DpopKey): string {<br>  const ref = randomUUID();<br>  store.set(ref, key);<br>  return ref;<br>}</pre><p>The token-exchange, refresh, and proxy paths resolve that reference back to the key server-side. The raw key never crosses the wire. The honest trade-off, documented as a POC limitation: an in-memory store is per-process, so a server restart or a second replica forces re-login. <br><em>A real deployment would swap in a shared secret store; the interface would not change</em>.</p><h4>Binding the very first token (the sharp edge)</h4><p>This is the one genuinely version-sensitive piece. The key has to exist and sign a proof <strong>before</strong> the authorization-code-to-token exchange, but that exchange happens deep inside next-auth’s Keycloak provider, and the callback where you would normally persist things runs <strong>after</strong> it. The trap is assuming you can bolt the proof on afterwards. You cannot; the proof has to be part of the token request itself.</p><p>The clean way through is to <a href="https://github.com/hcussi/nextjs-springboot-keycloak-poc/blob/main/frontend/src/lib/auth.ts#L126">override</a> the provider’s <em>token</em> request, generate the key there, and hand it to the underlying <em>openid-client</em> (which next-auth uses) to sign the proof for you:</p><pre>token: {<br>  async request({ client, params, checks, provider }) {<br>    const key = await generateDpopKeyPair();<br>    const tokenSet = await client.callback(provider.callbackUrl, params, checks, {<br>      DPoP: key.privateKey,   // openid-client signs the token-endpoint proof<br>    });<br>    const dpopKeyRef = putDpopKey(key);<br>    return { tokens: { ...tokenSet, dpopKeyRef } };<br>  },<br>},</pre><p>That <em>DPoP: key.privateKey</em> argument is the whole trick: <em>openid-client</em> already knows how to sign a token-endpoint proof. Everything downstream (refresh, resource calls) is in code we already own, so it is just a matter of adding a signed <em>DPoP</em> header.</p><h4>The BFF proxy: sign the proof, forward nothing extra</h4><p>The browser calls a same-origin route like <em>/api/backend/hello</em> with only its session cookie. The proxy reads the token and key server-side, signs a fresh resource proof (with <em>ath</em>), and forwards under the <em>DPoP</em> scheme:</p><pre>const proof = await signDpopProof({ key, htm: &quot;GET&quot;, htu: url, accessToken });<br>const backendResponse = await fetch(url, {<br>  method: &quot;GET&quot;,<br>  headers: { Authorization: `DPoP ${accessToken}`, DPoP: proof },<br>  cache: &quot;no-store&quot;,<br>});</pre><p>The rule that keeps this safe is the one that is easy to forget: <strong>do not relay the browser’s incoming headers.</strong> The session cookie carries the key-store reference and must never transit to (or be logged by) the backend. So the outbound request is built from a strict allow-list (<em>Authorization</em>, <em>DPoP</em>, <em>Content-Type</em>), and the response comes back through an allow-list too, deliberately including <em>WWW-Authenticate</em> so the browser can still read the RFC 9470 step-up challenge relayed from the backend. Because the proxy is same-origin, that challenge reaches the browser with no CORS gymnastics at all, and the step-up UX from the previous article keeps working unchanged.</p><h4>Bringing It Up</h4><p>The whole thing runs from <em>docker compose up</em>, and the end-to-end story is worth walking once:<br>1. <strong>Log in</strong> as <em>testuser</em>. next-auth’s <em>token</em> hook generates the ES256 key, signs the token-endpoint proof, and Keycloak returns an access token stamped with <em>cnf.jkt</em>. The key lands in the server-side store; only its opaque reference rides in the session cookie.<br>2. <strong>Load <em>/hello</em>.</strong> The browser calls the same-origin proxy with just its cookie. The proxy signs a fresh proof (<em>htm=GET</em>, <em>htu</em>, <em>ath</em>) and forwards under <em>Authorization: DPoP</em>. The backend validates the JWT <strong>and</strong> the proof, and returns the greeting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*l56jefDPqNBtX_g5K1c5DQ.png" /></figure><p>3. <strong>Click “Load server details.”</strong> The base token lacks <em>acr=pro</em>, so the backend answers with the RFC 9470 <em>insufficient_user_authentication</em> <em>401</em>, which the proxy relays untouched. The frontend catches it and begins step-up.<br>4. <strong>Complete TOTP.</strong> Keycloak re-issues an elevated token, still <em>cnf.jkt</em>-bound to the same key. The retry succeeds and <em>/server-details</em> renders, the level badge flips to <em>pro</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*23lZVsZfKA0PeGxKG2J9vQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*V7XpQCQVRB-tgfLi5E3Y0A.png" /></figure><p>5. <strong>Watch the refresh.</strong> Five minutes in, the token expires; the refresh grant carries a DPoP proof so the new token stays bound to the same key. <em>cnf.jkt</em> is stable across the whole session.<br>6. <strong>Try to cheat.</strong> Take that valid token and replay it with no proof, or a proof signed by a different key, or under <em>Authorization: Bearer</em>, or the same proof twice. Every one of them is a <em>401</em>. That row of negatives is the entire point of the iteration, and the headless e2e asserts all of them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nS6ikPqyhQWXKaTr9dZOlA.png" /></figure><h4>Wrapping Up</h4><p>DPoP sounds like it should be a major re-architecture. It is not. It is <strong>one key pair</strong>, <strong>one extra header</strong>, and <strong>one claim</strong> (<em>cnf.jkt</em>) that turns a token from a password into a certificate you have to prove you hold. The frontend signs a proof, Keycloak stamps the thumbprint, the backend checks the marriage on every request. A leaked token, alone, <strong>buys the attacker nothing</strong>.</p><p>Be precise about what that buys you, though, and do not oversell it. Because the key and the token co-locate in the Next.js tier, DPoP here defeats <strong>token-only leakage</strong>: a token in a log, a capture on the proxy-to-backend hop, an error tracker, browser XSS (already closed once the token stops reaching the browser). It does <strong>not</strong> defend a full compromise of the Next.js tier, which hands over both artifacts at once. That narrower guarantee is exactly the guarantee, and knowing its edges is part of using it well.</p><p>Everything is reproducible. Clone the <a href="https://github.com/hcussi/nextjs-springboot-keycloak-poc">repository</a>], add the one <em>127.0.0.1 keycloak</em> line to <em>/etc/hosts</em>, run <em>docker compose up</em>, and log in. Then open the network tab and confirm the thing that makes it all worthwhile: the browser makes only same-origin calls, and the access token and private key are nowhere to be found.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7f3b8d85fa9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prepare for an Interview with a Claude Skill and an Agent]]></title>
            <link>https://medium.com/@hernncussi/prepare-for-an-interview-with-a-claude-skill-and-an-agent-fbeb415f50b5?source=rss-82e8d590697f------2</link>
            <guid isPermaLink="false">https://medium.com/p/fbeb415f50b5</guid>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[job-interview]]></category>
            <category><![CDATA[job-interview-preparation]]></category>
            <category><![CDATA[ai-skills]]></category>
            <dc:creator><![CDATA[Hernán Cussi]]></dc:creator>
            <pubDate>Wed, 15 Jul 2026 01:32:09 GMT</pubDate>
            <atom:updated>2026-07-15T13:08:41.555Z</atom:updated>
            <content:encoded><![CDATA[<p>Turning a job description into a tailored interview study pack</p><p>When you prepare for a software interview, the hardest part is not knowing the material. Every role is a slightly different bet: this company runs Kotlin on Postgres, that one lives and dies by Kafka, a third wants you to reason about idempotency in a payments pipeline. Generic prep answers a generic interview. The interview you actually walk into is specific.</p><p>This is the story of pointing two small Claude Code tools at that problem. One writes a study pack tailored to a single job. The other reads it back and tells me, before I trust it, whether it is any good. The pack is real output I can open in a browser.</p><h4>The Problem: Prep That Fits Every Job and No Job</h4><p>Open any interview-prep site and you get the same thing: a wall of <strong>“top 50 backend questions,”</strong> none of them shaped for the company in front of you. It is not wrong. It is just untargeted. You spend the night before an interview reading about a hash map when the actual conversation is going to be about consistency models on their exact database.</p><p>I wanted the opposite. Given a job posting, I wanted a pack that named the company’s stack, framed system design around their product, and asked the questions an interviewer at <strong>that</strong> company would actually ask. Writing one by hand is a few hours of reading the JD, choosing topics, and drafting answers that read as senior rather than as flashcards. Doing it well, every time, for every role, is more discipline than most of us have at 11pm.</p><p>So I turned the authoring into a skill and the quality gate into an agent.</p><h4>The Toolkit: A Skill to Author, an Agent to Review</h4><p>There are two pieces, and they do very different jobs.</p><p>The <strong>skill</strong> (<a href="https://github.com/hcussi/claude-code-toolkit/tree/main/skills/interview-prep"><em>interview-prep</em></a><em>)</em> is the author. You hand it a job description, a URL or pasted text, and a size. It fetches the posting, detects the discipline and the stack, picks a topic track, and writes one content model. A small build script then compiles that model into two self-contained HTML editions: a <strong>tracker </strong>with per-section checkboxes and a progress ring that remembers where you stopped, and a <strong>reading</strong> edition that is just the material, clean and scrollable. Both come from the same source, so the content is written once and the presentation is fixed and known-good.</p><p>The <strong>agent</strong> (<a href="https://github.com/hcussi/claude-code-toolkit/blob/main/agents/interview-content-reviewer.md"><em>interview-content-reviewer</em></a><em>)</em> is the critic. It is read-only. It opens the pack the skill just wrote, checks it against the schema and the house style, runs the mechanical checks I would otherwise forget, and hands back a verdict: ship, fix first, or blocked. It does not touch the file. It tells me what is wrong and where, and lets me decide.</p><p>The skill is the driver. The agent is the second pair of eyes.</p><h4>Why a Skill and an Agent, Not Just One</h4><p>It would be tempting to fold the review into the skill and be done. I did not, and the reason is how each thing is built to run.</p><p>A subagent in Claude Code is a one-shot worker. You give it a job, it does the job in its own context, and it comes back with an answer. That shape is perfect for a review: <em>read everything, form a judgment, report, exit</em>.</p><p>Authoring is a <em>conversation, and conversations belong in a skill</em> that owns the loop. Review is a verdict, and a verdict belongs in an agent that reads with fresh eyes and no stake in what it is judging. <strong>Keeping the reviewer separate also keeps it honest. It did not write the content, so it has nothing to defend</strong>.</p><h4>How to Use Them</h4><p>Authoring is one line. You point the skill at the posting and tell it how deep to go.</p><pre>/interview-prep https://bitso.com/jobs/7777583003 size: large</pre><p>Everything before an optional pipe is the job. Everything after it is optional background, a resume or a portfolio, used to bias the depth toward what you already know. Size runs from <em>short</em>, a night-before refresher, to <em>xl</em>, a comprehensive pack with framework specifics and follow-up questions.</p><p>When it finishes, you review before you trust it:</p><pre>Use the interview-content-reviewer agent to review the interview pack</pre><p>Give the reviewer the raw job description and the size you asked for, and it gets sharper still, because it can check the pack against the real posting instead of inferring intent.</p><h4>What Made This Work</h4><p>I ran this for a real posting: the <a href="https://bitso.com/jobs/7777583003">Software Engineer role on Bitso’s Nexus team</a>, owning the pay-in and pay-out systems for a crypto platform with millions of users. Java at scale, Apache Kafka, event sourcing and CQRS, sagas, Postgres. The skill produced a pack of eight topics, sixteen reading blocks, and thirty-one questions, each one framed for money movement rather than for a textbook, where correctness, idempotency, and exactly-once reasoning matter more than raw features.<br>The result is two editions from one source. The tracker is for working through the pack over several days:<br><a href="https://github.com/hcussi/interview-prep/blob/main/bitso-prep/tracker.html">Tracker edition of the Bitso pack</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HWYnD-U521h8MXcyIGIgPQ.png" /></figure><p>The reading edition is the same content stripped to a clean, distraction-free scroll, with the questions as click-to-reveal cards:</p><p><a href="https://github.com/hcussi/interview-prep/blob/main/bitso-prep/reading.html">Reading edition of the Bitso pack</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*52AQV6iLJPcTB8inZehaTw.png" /></figure><h4>Try It Yourself</h4><p>Both tools live in the <a href="https://github.com/hcussi/claude-code-toolkit">claude-code-toolkit</a>, and installing them is a copy. Drop the <a href="https://github.com/hcussi/claude-code-toolkit/tree/main/skills/interview-prep"><em>interview-prep</em></a> skill into your project’s <em>.claude/skills/</em> directory and the <a href="https://github.com/hcussi/claude-code-toolkit/blob/main/agents/interview-content-reviewer.md"><em>interview-content-reviewer</em></a> agent into <em>.claude/agents/</em>, or put both under <em>~/.claude/</em> to make them available in every project. Claude Code picks them up with no further configuration.</p><pre>your-project/<br>  .claude/<br>    skills/<br>      interview-prep/<br>    agents/<br>      interview-content-reviewer.md</pre><p>From there it is one line to author and one to review. If you want to see the output before you run anything, a finished set of packs generated exactly this way lives in the <a href="https://github.com/hcussi/interview-prep">interview-prep repo</a>.</p><p>If you would rather not assemble anything, that same repo is the shortcut. Fork <a href="https://github.com/hcussi/interview-prep">interview-prep</a> and you get both the skill and the agent already wired up under <em>.claude/</em>, alongside example packs. Open it in Claude Code and you can generate your first pack immediately.</p><p>The shape is reusable well beyond interview prep. A skill that authors and a build step that renders, paired with a read-only agent that holds the output to a written bar, is a pattern you can drop onto anything where the work is <strong>“produce something, then make sure it is actually good.”</strong> Content, configs, migrations, release notes.</p><p>Start with the bar. Write down what “good” means concretely enough that an agent can check it. Then let the skill write the first draft, and let the agent argue with it until the pack says something you would actually want to walk into the room with.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fbeb415f50b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Redesigning an AI-Built UI with a Claude Code Agent and a Skill]]></title>
            <link>https://medium.com/@hernncussi/redesigning-an-ai-built-ui-with-a-claude-code-agent-and-a-skill-032cb9cb3dd6?source=rss-82e8d590697f------2</link>
            <guid isPermaLink="false">https://medium.com/p/032cb9cb3dd6</guid>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[ai-skills]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Hernán Cussi]]></dc:creator>
            <pubDate>Mon, 06 Jul 2026 14:13:12 GMT</pubDate>
            <atom:updated>2026-07-06T14:13:12.914Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Using a Playwright-driven design reviewer and a human-in-the-loop iterate skill to take a chat app from “default starter” to a real product look.</blockquote><p>When a large language model builds a web app from scratch, it usually works on the <a href="https://medium.com/@hernncussi/from-prompt-to-product-the-story-of-an-ai-built-chat-application-47639ca1b1e0">first try</a>. What it rarely does is look like anything. You get an indigo button, a slate-grey sidebar, the Tailwind defaults, and a layout that reads as “someone ran create-next-app.” <a href="https://github.com/hcussi/chat-ai">Chat AI</a> was exactly that: a fully functional Gemini chat client, multi-chat history, markdown rendering, usage stats, and a UI that quietly announced its origins.</p><p>This is the story of pointing two small tools at that UI and iterating it into something with intent. Both tools live in an open toolkit, <a href="https://github.com/hcussi/claude-code-toolkit">claude-code-toolkit</a>: an agent called <em>ui-design-reviewer</em> and a skill called <em>ui-iterate</em>. The interesting part is not just the result, it is how the two divide the work.</p><h4>The Problem: A Working App That Looks Like a Starter</h4><p>Chat AI is a Next.js 15 / React 19 / Tailwind 4 application. The functionality was never the issue. The look was. A quick pass over the source already tells you why it reads as generic:<br>- The accent color is indigo <em>#4f46e5</em>, Tailwind’s <em>indigo-600</em>. It is the single most recognizable “default framework” signal there is.<br>- Surfaces are flat panels with default spacing and borders.<br>- There is no visual identity that says “this is a chat product,” only that it is a React app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZHOz902v7bGGZ8tF9IChQA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*85d9CSc80GAzwC_a_-QAhA.png" /><figcaption>Before: functional, but indistinguishable from a starter template.</figcaption></figure><p>The goal was not a rewrite. It was to give the same app a considered visual system without touching its behavior.</p><h4>The Toolkit: An Agent to Critique, a Skill to Iterate</h4><p>Two pieces, with a deliberate split of responsibility.<br><a href="https://github.com/hcussi/claude-code-toolkit/blob/main/agents/ui-design-reviewer.md"><strong><em>ui-design-reviewer</em></strong></a> is a read-only agent. It does not read your intentions from the source, it drives the <strong>running</strong> app through the <a href="https://github.com/microsoft/playwright-mcp">Playwright MCP</a> and reports on what actually renders: screenshots at desktop, tablet, and mobile widths, hover and focus states, computed styles (the font that truly loads, real colors, spacing, measured contrast), and the accessibility tree. It returns a prioritized critique. It never edits code.<br><a href="https://github.com/hcussi/claude-code-toolkit/blob/main/skills/ui-iterate/SKILL.md"><strong><em>ui-iterate</em></strong></a> is a user-invoked skill. It owns the loop: render, critique, agree on the changes with you, edit the code, re-render, and show before and after, round after round, until you say it is good.</p><h4>Why a Skill and an Agent, Not Just One</h4><p>This is the part worth pausing on. A subagent in Claude Code is a one-shot worker: it is spawned, does its job, and returns. It cannot pause in the middle to ask you what you think, and a fresh spawn does not carry your earlier feedback.</p><p>“Iterate over and over according to feedback from the user” is, by definition, multi-turn and conversational. That does not belong inside a single agent run. So the loop lives in the main thread as a skill, and the skill calls the read-only agent for the autonomous critique each round.</p><p>Clean separation: <strong>the agent is the critic, the skill is the driver.</strong> The agent is a pure function (UI in, critique out); the skill is the stateful thing that edits files and talks to you.</p><h4>The Design Bar: Material-Informed Minimalism</h4><p>Both tools judge the UI against the same rubric: Material Design as the <strong>structural and behavioral</strong> guideline (an 8dp spacing grid, color roles, elevation, state layers, motion, accessibility), while respecting the product’s own palette and identity. Minimalism means restraint: every element has to earn its place, and whitespace is a feature.</p><p>The nuance that keeps this reusable: it does not force a generic Material look onto a product that has its own voice. It judges <strong>structure, behavior, and accessibility</strong> by Material, and <strong>identity</strong> on its own terms. A distinctive, non-default look is good, as long as it stays consistent, accessible, and restrained.</p><h4>How to use them</h4><p>Copy the agent and the skill into the project so Claude Code can find them:</p><pre>chat-ai/.claude/agents/ui-design-reviewer.md<br>chat-ai/.claude/skills/ui-iterate/</pre><p>Prompt something like</p><pre> Improve the ui design for this app  </pre><p>And check the results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_N4txs1RKnR2hl2Nd9q-FA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LD5gF07ZHSyfmLApBEicyQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wcGN19Y5VYYPaGL8NsTDNA.png" /></figure><p>Same features, same behavior, same tests passing. What changed is that the UI now looks like a decision instead of a default.</p><h4>What Made This Work</h4><p>A few things stood out:<br>- <strong>Measured, not guessed.</strong> Reviewing the running app through Playwright meant findings were about what renders, including the font that truly loads and the real contrast ratio, not what the source implies.<br>- <strong>The right tool for each job.</strong> A one-shot agent cannot hold a conversation; a skill can. Splitting critic from driver is what made “iterate with feedback” actually work.<br>- <strong>A rubric, not vibes.</strong> Material-informed minimalism gave every round a consistent bar, so the UI converged instead of wandering.<br>- <strong>The human stayed in charge.</strong> The tools accelerated the work; the taste and the stop condition were mine.</p><h4>Try It Yourself</h4><p>Everything here is reusable. The agent and skill are stack-agnostic; Chat AI just happened to be a convenient patient.</p><p>- The app: <a href="https://github.com/hcussi/chat-ai">github.com/hcussi/chat-ai</a><br>- The tools: <a href="https://github.com/hcussi/claude-code-toolkit">github.com/hcussi/claude-code-toolkit</a></p><p>Install the Playwright MCP, copy <em>ui-design-reviewer</em> and <em>ui-iterate</em> into your project’s <em>.claude/</em> directory, start your dev server, and run <em>/ui-iterate</em> on the screen you want to improve. Then argue with it until the UI looks like something you meant.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=032cb9cb3dd6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Step-Up Authentication with Keycloak, Spring Boot, and Next.js]]></title>
            <link>https://medium.com/@hernncussi/step-up-authentication-with-keycloak-spring-boot-and-next-js-9f4237009100?source=rss-82e8d590697f------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f4237009100</guid>
            <category><![CDATA[keycloak]]></category>
            <category><![CDATA[level-of-authentication]]></category>
            <category><![CDATA[stepup-authentication]]></category>
            <dc:creator><![CDATA[Hernán Cussi]]></dc:creator>
            <pubDate>Mon, 06 Jul 2026 01:32:13 GMT</pubDate>
            <atom:updated>2026-07-28T23:09:08.298Z</atom:updated>
            <content:encoded><![CDATA[<h4>One Login, Two Assurance Levels</h4><h4>Part 3 of the Next.js + Spring Boot + Keycloak series.</h4><p>In <a href="https://medium.com/@hernncussi/wiring-next-js-spring-boot-and-keycloak-with-the-oauth2-authorization-code-flow-7d2af701a248">Part 2</a> we stood up a <a href="https://github.com/hcussi/nextjs-springboot-keycloak-poc/blob/main/PRD.md">real login</a> through Keycloak with the Authorization Code flow (plus PKCE). One login, one assurance level, one gate.</p><p>But real systems are not that flat. Some endpoints are more sensitive than others. You want the everyday screens behind a normal password login, and the dangerous ones behind <strong>something more</strong>: a second factor, requested only when the user actually reaches for them.</p><p>That is <a href="https://github.com/hcussi/nextjs-springboot-keycloak-poc/blob/main/PRD-2.md"><strong>step-up authentication</strong></a>, and it is what this post wires end to end.</p><h4>The Big Picture</h4><p>We add one endpoint, <em>GET /server-details</em>, that demands a higher level than <em>/hello</em>. When a normally-logged-in user reaches for it, the backend does not just say “no.” It says, in a standards-defined way, “not good enough, come back with <em>acr=pro</em>,” and the frontend transparently re-authenticates the user at that higher level and retries. The base <em>/hello</em> login never changes.</p><p>Two assurance levels, one login, gated by what the client asks for:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gK2u91jJ_tf2tuDRhYt8vg.png" /><figcaption>Level of Authentication</figcaption></figure><p>And two endpoints, protected at those two levels:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4H-hwif0-4oOvH32HCrkUQ.png" /><figcaption>Endpoints and required LoA</figcaption></figure><p>The <a href="https://github.com/hcussi/nextjs-springboot-keycloak-poc/blob/main/PLAN-2.md">whole dance</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*smv4c6eqmmSw69cQyizI-g.png" /></figure><p>Three seams have to agree for this to work: Keycloak has to <strong>issue</strong> two different levels from the same login, the backend has to <strong>enforce</strong> the level and challenge correctly, and the frontend has to <strong>react</strong> to the challenge and retry.</p><h4>The Vocabulary: <em>ACR</em> and LoA</h4><p>Before the code, one concept that ties all three services together.</p><p><strong><em>ACR</em></strong> is the <strong>Authentication Context Class Reference</strong>, a standard OIDC claim. It is a string the identity provider stamps on the token to say “here is how strongly this user authenticated.” <strong>LoA</strong> (Level of Authentication) is the numeric ranking behind those strings. <strong>Keycloak</strong> connects the two with a realm attribute, <em>acr.loa.map</em>:</p><pre>&quot;attributes&quot;: {<br>  &quot;acr.loa.map&quot;: &quot;{\&quot;basic\&quot;:1,\&quot;pro\&quot;:2}&quot;<br>}</pre><p>So <em>basic</em> is level 1, <em>pro</em> is level 2. The frontend requests a named level (`pro`), <strong>Keycloak</strong> knows that means LoA 2, runs whatever the flow says <strong>LoA</strong> 2 requires, and stamps <em>acr=pro</em> on the resulting token. The backend then reads that one string off the token and decides. Everything downstream is just plumbing around this claim.</p><h4>Keycloak: Issuing Two Levels From One Login</h4><p>This is the hard part, and it is entirely realm configuration. No code. The goal is a single <strong>browser flow</strong> that runs the password step for everyone and the TOTP step <strong>only when LoA 2 is requested</strong>, so that base login stays byte-for-byte what it was in <a href="https://medium.com/@hernncussi/wiring-next-js-spring-boot-and-keycloak-with-the-oauth2-authorization-code-flow-7d2af701a248">Part 2</a>.</p><h4>The conditional flow</h4><p><strong>Keycloak</strong>’s browser flow is a tree of executions. We replace the default with a custom <a href="https://github.com/hcussi/nextjs-springboot-keycloak-poc/blob/main/keycloak/realm-export.json#L262"><em>browser-stepup</em></a> flow built around the <strong>Conditional — Level of Authentication</strong> authenticator:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pmgK6RoymV2oWgVzr5GIUQ.png" /><figcaption>Browser Authentication</figcaption></figure><p>Read it top to bottom. The <em>Cookie</em> execution is <em>ALTERNATIVE</em>, so an existing SSO session can satisfy the base level without a re-login, exactly as before. Inside <em>stepup-forms</em>, the two conditional subflows each guard themselves with a <em>Condition — LoA</em> check: the LoA-1 subflow runs its password form only when level 1 is the target, and the LoA-2 subflow runs its <strong>OTP form</strong> only when level 2 is requested.</p><p>That is the whole trick. Ask for nothing, get the password path, <em>acr=basic</em>. Ask for <em>pro</em>, and the LoA-2 condition fires and forces the OTP form on top, <em>acr=pro</em>. <em>/hello</em>’s login is untouched because nobody asks for <em>pro</em> on the way to it.</p><h4>The one setting that makes the challenge real: `max-age 0`</h4><p>Look again at the two conditions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mCokYeG6lNiw-BghzRIOuw.png" /></figure><p><em>loa-max-age</em> on the LoA-2 condition is <em>0</em>, and that is deliberate, but be precise about what it controls. <strong>Max-age</strong> governs Keycloak’s behavior at the <strong>authorization-request boundary</strong>: each time the frontend actually redirects to Keycloak asking for <em>pro</em>. It is how long Keycloak will consider a previously-achieved level still “fresh” when a <strong><em>new</em></strong> <em>pro</em> request arrives inside an existing session. With a non-zero value, a second <em>pro</em> authorization request could be satisfied <strong>silently</strong> from the prior elevation (or from the base SSO cookie), skipping the OTP form. That is exactly what you want in production to avoid step-up fatigue. Setting it to <em>0</em> means “no prior elevation is ever fresh enough; run the OTP form again,” which is what forces a real re-challenge inside an existing session, the safety-critical property here, and what makes each fresh end-to-end run deterministic. A real deployment would raise this to, say, five minutes. It is called out as a demo-determinism choice, not a recommendation.</p><p>What <em>max-age 0</em> does <strong>not</strong> do: force OTP on every <em>/server-details</em> click. It only touches authorization requests, not reuse of a token you already hold. Once step-up succeeds, the frontend has a <em>pro</em> access token in the session; subsequent clicks reuse that token, the backend sees <em>acr=pro</em> and returns <em>200</em>, and no redirect to Keycloak happens, so there is nothing for max-age to evaluate and no second OTP prompt. Token refresh behaves the same way: the <em>refresh_token</em> grant preserves the session’s achieved level, so the refreshed token stays <em>pro</em> without re-running OTP. So within one session you see the OTP <strong>once per step-up, not once per click</strong>, and the elevation lasts for the SSO session lifetime. A leaked <em>pro</em> token is therefore reusable for its lifetime, which is accepted for this POC.</p><h4>Getting ACR onto the access token</h4><p>Here is a trap that will cost you an afternoon if you miss it. By default, OIDC puts <em>acr</em> in the <strong>ID token</strong>. But our backend is a resource server: it enforces on the <strong>access token</strong> the frontend forwards as a <strong>Bearer credential</strong>. If <em>acr</em> is only in the ID token, the backend never sees it, the <em>pro</em> authority is never granted, and <em>/server-details</em> is challenged <strong>forever</strong>, even with a perfectly good <em>pro</em> token. It fails closed, and it fails invisibly.</p><p>The fix is to make sure <em>acr</em> is emitted on the access token. <strong>Keycloak</strong> ships a built-in <em>acr</em> client scope for exactly this; we add it to the client’s default scopes:</p><pre>&quot;defaultClientScopes&quot;: [&quot;web-origins&quot;, &quot;acr&quot;, &quot;roles&quot;, &quot;profile&quot;, &quot;basic&quot;, &quot;email&quot;]</pre><p>With that <strong>scope active</strong>, the <em>acr</em> claim rides along on the access token, and the backend can read it. Decode your access token and confirm <em>acr</em> is actually there before you trust any of the enforcement below. This one check saves the most debugging.</p><h4>The seed second factor</h4><p>For a one-command, no-manual-steps demo, the seed user’s TOTP credential is baked into the realm export with a known secret, and the OTP policy is pinned so the code is reproducible:</p><pre>&quot;otpPolicyType&quot;: &quot;totp&quot;, &quot;otpPolicyAlgorithm&quot;: &quot;HmacSHA1&quot;,<br>&quot;otpPolicyDigits&quot;: 6, &quot;otpPolicyPeriod&quot;: 30, &quot;otpPolicyLookAheadWindow&quot;: 1</pre><pre>{ &quot;type&quot;: &quot;otp&quot;,<br>  &quot;secretData&quot;: &quot;{\&quot;value\&quot;:\&quot;stepupTOTPseedDEVonly1234567890AB\&quot;}&quot;,<br>  &quot;credentialData&quot;: &quot;{\&quot;subType\&quot;:\&quot;totp\&quot;,\&quot;digits\&quot;:6,\&quot;period\&quot;:30,\&quot;algorithm\&quot;:\&quot;HmacSHA1\&quot;}&quot; }</pre><p>Because the secret and the policy are both fixed and known, a script (or the automated test) can compute the current 6-digit code with plain <em>node:crypto</em> and complete the flow with no browser.</p><blockquote>The realm also disables self-service TOTP enrollment and turns on brute-force protection, because the OTP now guards a privileged level.</blockquote><h4>Spring Boot: Enforce the Level, Challenge Correctly</h4><p>The backend has two jobs now: gate <em>/server-details</em> on the <em>pro</em> level, and when a valid-but-under-assured token shows up, answer with a <strong>standards-based step-up challenge</strong> instead of a bare, uninformative <em>403</em>.</p><h4>Mapping ACR to an authority</h4><p>Spring Security thinks in authorities. So we teach it to turn the token’s <em>acr</em> claim into one. A custom <a href="https://github.com/hcussi/nextjs-springboot-keycloak-poc/blob/main/backend/src/main/java/com/poc/backend/config/SecurityConfig.java#L69"><em>JwtAuthenticationConverter</em></a> keeps the default scope/role authorities and <strong>adds</strong> an <em>ACR_&lt;value&gt;</em> authority derived from the claim:</p><pre>private JwtAuthenticationConverter acrAuthenticationConverter() {<br>    JwtGrantedAuthoritiesConverter defaultAuthorities = new JwtGrantedAuthoritiesConverter();<br>    JwtAuthenticationConverter converter = new JwtAuthenticationConverter();<br>    converter.setJwtGrantedAuthoritiesConverter(jwt -&gt; {<br>        Collection&lt;GrantedAuthority&gt; authorities = new ArrayList&lt;&gt;(defaultAuthorities.convert(jwt));<br>        String acr = jwt.getClaimAsString(&quot;acr&quot;);<br>        if (acr != null &amp;&amp; !acr.isBlank()) {<br>            authorities.add(new SimpleGrantedAuthority(&quot;ACR_&quot; + acr.strip()));<br>        }<br>        return authorities;<br>    });<br>    return converter;<br>}</pre><p>A <em>pro</em> token now carries <em>ACR_pro</em>. A base token carries <em>ACR_basic</em>. The <a href="https://github.com/hcussi/nextjs-springboot-keycloak-poc/blob/main/backend/src/main/java/com/poc/backend/config/SecurityConfig.java#L54">authorization rule</a> falls out naturally:</p><pre>.authorizeHttpRequests(auth -&gt; auth<br>    .requestMatchers(&quot;/server-details&quot;).hasAuthority(stepUpAuthority)  // ACR_pro<br>    .anyRequest().authenticated())</pre><p>Note what is <strong>not</strong> here: the required level is not a hardcoded <em>”pro”</em>. It comes from <a href="https://github.com/hcussi/nextjs-springboot-keycloak-poc/blob/main/backend/src/main/resources/application.yml#L22">config</a>, <em>app.security.stepup.acr</em> (default <em>pro</em>), and is <em>strip()</em>-ed so a stray space cannot silently make the authority unmatchable and lock everyone out. If Keycloak’s level name ever changes, that is a one-line config edit, and a test asserts the two stay in sync.</p><h4>The RFC 9470 challenge</h4><p>When a <em>basic</em> token hits <em>/server-details</em>, it is authenticated but not authorized. Spring’s default response is a <em>403 Forbidden</em>, which tells the client nothing actionable. We want to tell it precisely: <strong>you are not wrong to be here, you are just not elevated enough, and here is the level to request.</strong> That contract is standardized in <strong>RFC 9470</strong>, and we emit it with a custom <a href="https://github.com/hcussi/nextjs-springboot-keycloak-poc/blob/main/backend/src/main/java/com/poc/backend/config/StepUpAccessDeniedHandler.java#L40"><em>AccessDeniedHandler</em></a>:</p><pre>public void handle(HttpServletRequest request, HttpServletResponse response,<br>                   AccessDeniedException ex) throws IOException {<br>    if (lacksRequiredLevel()) {<br>        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);        // 401, not 403<br>        response.setHeader(&quot;WWW-Authenticate&quot;,<br>            &quot;Bearer error=\&quot;insufficient_user_authentication\&quot;, &quot;<br>            + &quot;error_description=\&quot;A higher authentication level is required\&quot;, &quot;<br>            + &quot;acr_values=\&quot;&quot; + requiredAcr + &quot;\&quot;&quot;);<br>    } else {<br>        response.sendError(HttpServletResponse.SC_FORBIDDEN);<br>    }<br>}</pre><p>The status is deliberately <em>401</em> with a <em>WWW-Authenticate</em> header, not <em>403</em>. The header names the error (<em>insufficient_user_authentication</em>) and, crucially, the required level (<em>acr_values=”pro”</em>). This is the <strong>machine-readable instruction the frontend follows</strong>. And it only fires for a genuinely under-assured principal; any other kind of denial still falls through to a plain <em>403</em> rather than being mislabeled as a step-up prompt. A missing or invalid token never reaches this handler at all: that is an <strong>authentication</strong> failure, handled by the resource server’s ordinary <em>401</em> entry point.</p><h4>The CORS detail that is easy to forget</h4><p>The frontend is a browser <em>fetch</em> on a different origin. <strong>A browser cannot read a response header unless CORS explicitly exposes it.</strong> Emit the perfect RFC 9470 challenge and forget this one line, and the frontend’s <em>fetch</em> sees a <em>401</em> with an empty header, cannot find <em>acr_values</em>, and step-up silently never triggers:</p><pre>config.setExposedHeaders(List.of(&quot;WWW-Authenticate&quot;));</pre><p>This is the seam that quietly breaks first attempts. The challenge is correct on the wire; the browser just is not allowed to look at it.</p><h4>Next.js: React to the Challenge, Then Retry</h4><p>The frontend’s job: when a <em>/server-details</em> call comes back as a step-up challenge, read the required level, re-run the OIDC login asking for it, then retry the original call and render the result. All of it should feel like one click.</p><h4>Reading the challenge and deciding to <a href="https://github.com/hcussi/nextjs-springboot-keycloak-poc/blob/main/frontend/src/app/page.tsx#L85">step up</a></h4><pre>const res = await fetch(`${API_URL}/server-details`, {<br>  headers: { Authorization: `Bearer ${accessToken}` },<br>});<br>if (res.ok) { setServerDetails(await res.json()); return; }<br><br>// Readable only because the backend exposes WWW-Authenticate via CORS.<br>const challenge = res.headers.get(&quot;WWW-Authenticate&quot;) ?? &quot;&quot;;<br>const isStepUp =<br>  res.status === 401 &amp;&amp; challenge.includes(&quot;insufficient_user_authentication&quot;);<br>if (isStepUp &amp;&amp; allowStepUp) {<br>  const required = parseAcrValues(challenge);<br>  if (required &amp;&amp; KNOWN_ACRS.includes(required)) {<br>    beginStepUp(required);   // navigates away to Keycloak<br>    return;<br>  }<br>}</pre><p>One security note hides in that <em>KNOWN_ACRS.includes(required)</em> check. The <em>acr_values</em> string comes from a response header, over plain HTTP, and is rewritable by anyone on-path. We are about to feed it into an authorization redirect. So we <strong>allow-list it against the known set</strong> (<em>[“pro”]</em>) before use, and never forward arbitrary header content into a redirect parameter.</p><h4>Requesting the higher level</h4><p>next-auth v4 lets us pass extra authorization parameters through <em>signIn</em>. We request the level two ways: the OIDC <em>claims</em> parameter with an <strong>essential</strong> <em>acr</em>, which is the binding channel per OIDC Core, plus <em>acr_values</em> as the compatibility hint:</p><pre>function beginStepUp(acr: string) {<br>  sessionStorage.setItem(STEPUP_MARKER, String(Date.now()));   // one-shot retry marker<br>  signIn(&quot;keycloak&quot;, { callbackUrl: &quot;/&quot; }, {<br>    claims: JSON.stringify({ id_token: { acr: { essential: true, values: [acr] } } }),<br>    acr_values: acr,<br>  });<br>}</pre><p>That <em>claims</em> line has two details worth unpacking.</p><p>First, <strong>why <em>JSON.stringify</em>.</strong> OIDC defines <em>claims</em> as a <strong>JSON-serialized string </strong>carried in the authorization request’s query string. <em>next-auth</em>’s <em>signIn</em> third argument is just a bag of extra query parameters it appends to the <em>/authorize</em> URL, and everything in a URL query is a string, so it forwards our string verbatim as <em>?claims=%7B%22id_token%22…</em>..</p><p>Second, <strong>why the <em>id_token</em> key.</strong> That is the shape of the OIDC claims request. It has two possible top-level members, <em>”userinfo”</em> and <em>”id_token”</em>, each saying <strong>which</strong> claims you want and <strong>where</strong>. <em>id_token</em> is the member that requests claims on the token-issuance path, and <em>{ essential: true, values: [“pro”] }</em> is an OIDC “individual claim request”: this <em>acr</em> claim is <strong>essential</strong> (required) and must be one of these values. OIDC Core §5.5.1.1 names this essential-<em>acr</em>-under-<em>id_token</em> form as <strong>the</strong> defined way to request a specific <em>acr</em>; the top-level <em>acr_values</em> parameter is explicitly only a voluntary hint, which is why we send both, binding channel plus compatibility hint.</p><p>Crucially, <em>id_token</em> here selects the <strong>request semantics</strong>, not which token the claim lands in. Keycloak reads the <em>id_token</em> member of the <em>claims</em> parameter to determine the requested <strong>LoA</strong>, and that is what drives the <strong>Conditional-LoA authenticator</strong> to fire the OTP step. The resulting <em>acr</em> still ends up on the <strong>access</strong> token (what the Spring backend enforces on) because of the separate <em>acr</em> client scope from the Keycloak section. The two are independent: <em>claims.id_token.acr</em> drives the flow; the <em>acr</em> scope controls emission onto the access token.</p><p>This navigates the whole page to Keycloak, which (because we asked for <em>pro</em>) runs the OTP form. There is no way to keep in-memory state across a full-page redirect, so before leaving we <a href="https://github.com/hcussi/nextjs-springboot-keycloak-poc/blob/main/frontend/src/app/page.tsx#L156">drop</a> a <strong>one-shot, time-bounded marker</strong> in <em>sessionStorage</em>. On return, an effect consumes it exactly once:</p><pre>useEffect(() =&gt; {<br>  if (status !== &quot;authenticated&quot; || !accessToken) return;<br>  const ts = consumeStepUpMarker();               // reads and clears in one shot<br>  if (ts !== null &amp;&amp; Date.now() - ts &lt;= STEPUP_MARKER_TTL) {<br>    queueMicrotask(() =&gt; void loadServerDetails(false));   // note: allowStepUp = false<br>  }<br>}, [status, accessToken, loadServerDetails]);</pre><p>The marker is cleared <strong>before</strong> the retry runs, so it can never replay against a later, unrelated navigation. And the retry passes <em>allowStepUp = false</em>: if that second call somehow still fails the level check, we toast the user rather than bounce them through Keycloak again in a loop. A cancelled or failed OTP lands back on the home page with an error toast, base session and <em>/hello</em> fully intact.</p><h4>Keeping the session’s ACR honest</h4><p>The session carries <em>acr</em> as a UI hint (so the button can tell “already elevated” from “needs step-up” and skip a redundant round-trip). The subtle bug to avoid: caching it only at initial sign-in. If the token refreshes to a different level, a stale <em>session.acr</em> would make the UI skip a step-up it still needs. So we re-derive <em>acr</em> from the access token on every <em>jwt</em> pass, including after a refresh, never from a cached copy:</p><pre>function acrOf(accessToken?: string): string | undefined {<br>  if (!accessToken) return undefined;<br>  const payload = JSON.parse(<br>    Buffer.from(accessToken.split(&quot;.&quot;)[1], &quot;base64url&quot;).toString(&quot;utf8&quot;));<br>  return typeof payload.acr === &quot;string&quot; ? payload.acr : undefined;<br>}</pre><p>Even so, this is only a hint. Enforcement is server-side, always. The UI can be wrong about the level and the worst outcome is one redundant challenge, never a bypass, because the backend re-checks the real claim on every request.</p><h4>The Same Login Yields Two Levels</h4><p>Step back and notice what did <strong>not</strong> change. There is still exactly one login flow, one client, one issuer, one session. We did not build a second “admin login.” We did not fork the frontend into two auth paths. The base <em>/hello</em> experience from <a href="https://medium.com/@hernncussi/wiring-next-js-spring-boot-and-keycloak-with-the-oauth2-authorization-code-flow-7d2af701a248">Part 2</a> is behaviorally identical.</p><p>Everything hangs on a single idea: <strong>the assurance level is a property of the request, not of the user or the app.</strong> The client asks for <em>pro</em>; Keycloak’s conditional flow decides that means “also run OTP”; the token comes back stamped <em>acr=pro</em>; the backend reads that one string and opens the gate. Nobody hardcodes “this user is privileged.” The elevation is requested, proven, and stamped, per request, and it evaporates when the token does.</p><p>That is why the three pieces stay so small. The Keycloak change is one conditional flow and a scope. The backend change is one authority mapping and one challenge handler. The frontend change is “read a header, re-login asking for more, retry once.” The <em>acr</em> claim is the thin wire that carries the decision across all three, and RFC 9470 is the agreed-upon language for one service to tell another “not enough, come back with <strong>this</strong>.”</p><h4>Bringing It Up: One Request, End to End</h4><p>From a clean checkout, <em>docker compose up — build</em> brings Keycloak (realm auto-imported, step-up flow and seed factor included), the backend, and the frontend up behind health checks. Add the one <em>/etc/hosts</em> line from Part 2 (<em>127.0.0.1 keycloak</em>) so the browser and backend agree on the issuer, and trace a single step-up from the top:</p><p>1. <strong>Log in</strong> as <em>testuser</em> at <em>http://localhost:3000</em>. Password only. You get a <em>basic</em> session, and <em>/hello</em> renders its greeting exactly as before. Nothing new yet.<br>2. <strong>Click “Load server details.”</strong> The frontend <em>fetch</em>es <em>GET /server-details</em> with the <em>basic</em> Bearer token.<br>3. <strong>The backend refuses, and says how.</strong> The token is valid but carries <em>ACR_basic</em>, not <em>ACR_pro</em>. The <em>AccessDeniedHandler</em> returns <em>401</em> with <em>WWW-Authenticate: Bearer error=”insufficient_user_authentication”, acr_values=”pro”</em>. CORS exposes that header, so the browser can read it.<br>4. <strong>The frontend steps up.</strong> It parses <em>acr_values=”pro”</em>, allow-lists it, drops the one-shot retry marker, and <em>signIn</em>s to Keycloak requesting <em>pro</em> via the essential-<em>acr</em> <em>claims</em> parameter.<br>5. <strong>Keycloak forces the second factor.</strong> This is a fresh <em>pro</em> authorization request, and with <em>max-age 0</em> the LoA-2 condition fires rather than being satisfied silently by the existing session, so the OTP form appears, the user enters the current TOTP code. Keycloak mints fresh tokens, now stamped <em>acr=pro</em>.<br>6. <strong>The frontend retries, once, automatically.</strong> Back on the home page, the marker is consumed, the <em>server-details</em> call reruns with the <em>pro</em> token, the backend sees <em>ACR_pro</em>, and returns <em>200</em> with the JVM version, uptime, active profiles, hostname, and server time. The panel renders. From the user’s side, that was one click and one OTP prompt.</p><p>The whole path is covered headlessly too. A dependency-free script computes the TOTP from the pinned seed and drives the exact same flow, asserting the `basic` challenge, the OTP step-up, and the <em>pro</em> success, so the behavior is a test, not a screenshot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BUqZhp1uR9-HrsVl3NwwEA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aMLqcJ-E0NhoHig-orhONg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N3joFJ5GwlhNmVDwehpYLQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*fmp5MUY3rZ7h41_x4ekMtQ.png" /></figure><h4>Wrapping Up</h4><p>Step-up sounds like it should be a big feature: a second authentication system bolted onto the first. It is not. It is <strong>one claim, ‘acr’, agreed upon by three services</strong>, plus a standard way (RFC 9470) for the backend to say “not enough, come back with more.”</p><p>Keycloak issues two levels from one login by wrapping the OTP form in a condition that only fires when <em>pro</em> is asked for. Spring Boot maps the claim to an authority, gates the sensitive endpoint on it, and answers an under-assured request with a <em>401</em> challenge instead of an opaque <em>403</em>. Next.js reads that challenge, re-logs in asking for the named level, and retries once. The base login never moves. There is, again, very little novel code here: the work is getting a handful of settings, a claim, and a header to agree.</p><p>Clone the repository, add the one <em>/etc/hosts</em> line, run <em>docker compose up</em>, and click “Load server details.” Watch a normal session get politely turned away, prove a little more, and get let in.</p><p>Continue in <a href="https://medium.com/@hernncussi/making-a-stolen-oauth-token-useless-dpop-in-practice-b7f3b8d85fa9">Part 4</a> with DPoP.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f4237009100" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Wiring Next.js, Spring Boot, and Keycloak with the OAuth2 Authorization Code Flow]]></title>
            <link>https://medium.com/@hernncussi/wiring-next-js-spring-boot-and-keycloak-with-the-oauth2-authorization-code-flow-7d2af701a248?source=rss-82e8d590697f------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d2af701a248</guid>
            <category><![CDATA[spring-security]]></category>
            <category><![CDATA[oauth2]]></category>
            <category><![CDATA[nextauth]]></category>
            <category><![CDATA[pkce]]></category>
            <category><![CDATA[keycloak]]></category>
            <dc:creator><![CDATA[Hernán Cussi]]></dc:creator>
            <pubDate>Wed, 01 Jul 2026 15:52:36 GMT</pubDate>
            <atom:updated>2026-07-06T14:36:35.947Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>A hands-on walk through a complete OIDC integration: the Authorization Code flow with PKCE, the Keycloak realm, a Spring Boot resource server, and next-auth, and the one detail that makes token validation work on both sides.</blockquote><h4>Part 2 of a series</h4><p>In <a href="https://medium.com/@hernncussi/building-an-oauth2-poc-with-an-ai-coding-agent-a80addd933da">the first post</a>, I covered the workflow that produced <a href="https://github.com/hcussi/nextjs-springboot-keycloak-poc">this proof of concept</a>: a document-first way of building with an AI coding agent. This post ignores all of that and goes straight into the code, the <strong>OAuth2 flow</strong> and the actual configuration across the three services. You do not need to have read part one to follow along.</p><h4>The Beginning</h4><p>Have you ever tried to stand up a <strong>real</strong> login across a single-page frontend, a stateless API, and a dedicated identity provider, only to get stuck on a token your backend refuses to accept? The individual pieces are documented everywhere. The friction is always in the seams: which OAuth2 flow, who holds the client secret, what the <em>iss</em> and<em> aud</em> claims must look like, and how the browser and the backend can possibly agree on all of it.</p><p>This post is a technical tour of a working proof of concept that ties three services together with OpenID Connect:<br>- <strong>Frontend</strong>: Next.js 16 (<em>App Router, TypeScript</em>) using <a href="https://next-auth.js.org/"><strong>next-auth v4</strong></a> with the Keycloak provider.<br>- <strong>Backend</strong>: Spring Boot 4 (Java 25) configured as an OAuth2 Resource Server.<br>- <strong>Identity provider</strong>: Keycloak 26, importing a pre-configured realm on startup.</p><p>A user logs in through Keycloak, the frontend receives a JWT access token, and it calls one protected endpoint (<em>GET /hello</em>) that validates that token before answering. Let us follow the token from click to <em>200 OK</em>.</p><h4>The Big Picture</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ifXZoOId6NRlPiKZ9RZyLg.png" /><figcaption>Login flow</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*69YPPXUjQKdB4aGwt9m8OA.png" /><figcaption>Technology stack</figcaption></figure><h4>Why the Authorization Code Flow (with PKCE)</h4><p><a href="https://datatracker.ietf.org/doc/html/rfc6749"><strong>OAuth2</strong></a> has several grant types, and choosing correctly is most of the security work. This integration uses the <a href="https://datatracker.ietf.org/doc/html/rfc6749#section-4.1">Authorization Code flow</a> with PKCE, for concrete reasons:<br>- The user authenticates <strong>directly with Keycloak</strong>, never handing credentials to the frontend or backend. Keycloak returns a short-lived, single-use <strong>authorization code</strong> to a pre-registered redirect URI.<br>- That code is then exchanged for tokens <strong>server-side</strong> (<em>in the Next.js server runtime</em>), so the confidential client secret never touches the browser.<br>- <strong>PKCE</strong> (Proof Key for Code Exchange, <em>S256</em>) binds the code exchange to the party that started the flow. The client sends a <em>code_challenge</em> up front and must present the matching <em>code_verifier</em> to redeem the code, which closes off authorization-code interception.</p><p>The flow, step by step:<br>1. The user clicks <strong>Log in</strong>. <em>next-auth</em> redirects the browser to Keycloak’s <em>/authorize</em> endpoint with <em>response_type=code</em>, the <em>client_id</em>, the <em>redirect_uri</em>, a <em>state</em>, and a PKCE <em>code_challenge</em>.<br>2. The user authenticates on Keycloak’s own login page.<br>3. Keycloak redirects back to the app’s callback with a one-time <em>code</em>.<br>4. The Next.js server exchanges the <em>code</em> (plus the <em>code_verifier</em> and the client secret) at Keycloak’s <em>/token</em> endpoint for an <a href="https://datatracker.ietf.org/doc/html/rfc6749#section-1.4"><strong>access token</strong></a>, an <a href="https://openid.net/specs/openid-connect-core-1_0.html#IDToken"><strong>ID token</strong></a>, and a <a href="https://datatracker.ietf.org/doc/html/rfc6749#section-1.5"><strong>refresh token</strong></a>.<br>5. The access token (a JWT) is sent as <em>Authorization: Bearer &lt;token&gt;</em> to the Spring Boot API.<br>6. The API validates the JWT and responds.</p><p>Everything below is the configuration that makes those six steps line up.</p><h4>Keycloak: the Realm Configuration</h4><p>Keycloak imports a <a href="https://github.com/hcussi/nextjs-springboot-keycloak-poc/blob/main/keycloak/realm-export.json"><em>realm-export.json</em></a> on first boot, so the identity provider is fully configured with no manual clicking. Here are the parts that matter.</p><p>Realm-level token and session settings:</p><pre>{<br>  &quot;realm&quot;: &quot;web&quot;,<br>  &quot;enabled&quot;: true,<br>  &quot;accessTokenLifespan&quot;: 300,<br>  &quot;ssoSessionIdleTimeout&quot;: 1800,<br>  &quot;ssoSessionMaxLifespan&quot;: 3600,<br>  &quot;revokeRefreshToken&quot;: true,<br>  &quot;refreshTokenMaxReuse&quot;: 0<br>}</pre><p>Access tokens live for <strong>5 minutes</strong> (<em>accessTokenLifespan: 300</em>). That short lifetime is deliberate: it forces the refresh path to be real, not theoretical. <em>revokeRefreshToken: true</em> with <em>refreshTokenMaxReuse: 0</em> makes refresh tokens <strong>single-use</strong> (rotation), so a replayed refresh token is rejected.</p><p>The two session settings bound how long that refresh loop can continue. <em>ssoSessionIdleTimeout: 1800</em> ends the session after <strong>30 minutes of inactivity</strong>, and <em>ssoSessionMaxLifespan: 3600</em> caps it at a hard <strong>1 hour</strong> regardless of activity. So the access token is rotated roughly <strong>every 5 minutes</strong>, but once either limit is hit the session dies and the user has to log in again.</p><p>Reading that config as a set of decisions:<br>- <em>publicClient: false</em> plus a <em>client-secret</em>: this is a <strong>confidential client</strong>. The secret is held server-side by <strong>next-auth</strong>, never shipped to the browser.<br>- <em>standardFlowEnabled: true</em> turns on the <strong>Authorization Code flow</strong>. <em>directAccessGrantsEnabled: false</em> turns<strong> off</strong> the password grant, so no one can trade a <strong>username/password directly for a token</strong>.<br>- <em>pkce.code.challenge.method: S256</em> makes Keycloak <strong>require</strong> PKCE for this client. A code exchange with no verifier is refused.<br>- <em>redirectUris</em> and <em>webOrigins</em> are exact, no wildcards. Keycloak only redirects back to the one callback URL next-auth actually uses.<br>- <em>fullScopeAllowed: false</em> applies <strong>least privilege</strong>: the client does not automatically inherit every role in the realm.</p><p><strong>The audience mapper</strong> is easy to miss but important. By default, a Keycloak access token’s <em>aud</em> claim may not name your API, and a resource server that only checks the signature and issuer would then accept <strong>any</strong> token the realm minted, including one meant for a different client (a confused-deputy problem). A protocol mapper fixes the audience explicitly:</p><pre>&quot;protocolMappers&quot;: [<br>  {<br>    &quot;name&quot;: &quot;audience&quot;,<br>    &quot;protocolMapper&quot;: &quot;oidc-audience-mapper&quot;,<br>    &quot;config&quot;: {<br>      &quot;included.client.audience&quot;: &quot;nextjs-frontend&quot;,<br>      &quot;access.token.claim&quot;: &quot;true&quot;<br>    }<br>  }<br>]</pre><p>Now every access token carries <em>aud: [“nextjs-frontend”]</em>, and the backend can require it.</p><h4>Spring Boot: the Resource Server</h4><p>The backend does one job on the auth side: <em>validate the JWT on every request</em>. Spring Security’s OAuth2 Resource Server support makes the happy path a few lines, and the audience check adds a few more.</p><p><a href="https://github.com/hcussi/nextjs-springboot-keycloak-poc/blob/main/backend/src/main/resources/application.yml"><em>application.yml</em></a> points at the issuer. Spring uses it to fetch the <a href="https://datatracker.ietf.org/doc/html/rfc7517">JWKS</a> (for signature verification) and to check the <em>iss</em> claim:</p><pre>spring:<br>  security:<br>    oauth2:<br>      resourceserver:<br>        jwt:<br>          issuer-uri: ${KEYCLOAK_ISSUER:http://keycloak:8081/realms/web}<br><br>app:<br>  security:<br>    jwt:<br>      audience: ${JWT_AUDIENCE:nextjs-frontend}<br><br>server:<br>  port: 8080</pre><p><strong>Where the JWKS actually lives</strong>. Notice that <em>application.yml</em> only names the <em>issuer-uri</em>, not a key URL. Spring resolves the rest through OIDC discovery: it fetches the realm’s discovery document and reads the <em>jwks_uri</em> field from it. For the issuer <em>http://keycloak:8081/realms/web</em>, the relevant endpoints are:</p><blockquote>Discovery: http://keycloak:8081/realms/web/.well-known/openid-configuration<br>JWKS: http://keycloak:8081/realms/web/protocol/openid-connect/certs</blockquote><p>The <em>…/protocol/openid-connect/certs</em> endpoint returns the realm’s public signing keys (the JSON Web Key Set). Spring fetches and caches them, then verifies each incoming token’s RS256 signature locally against the key whose <em>kid</em> matches the token header, so it never has to call Keycloak per request. This is also why the issuer must resolve to the same host on both sides: the backend reaches this JWKS URL over the Docker network, and the <em>iss</em> claim it validates has to match that exact string (see the <strong>One Issuer</strong> section).</p><p><strong>The </strong><a href="https://github.com/hcussi/nextjs-springboot-keycloak-poc/blob/main/backend/src/main/java/com/poc/backend/config/SecurityConfig.java#L30"><strong>security filter chain</strong></a> requires a valid JWT for every request, enables the resource server, and scopes CORS to the frontend origin so the browser fetch to <em>/hello</em> is allowed:</p><pre>@Bean<br>SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {<br>    http<br>        .cors(Customizer.withDefaults())<br>        .csrf(csrf -&gt; csrf.disable())<br>        .authorizeHttpRequests(auth -&gt; auth.anyRequest().authenticated())<br>        .oauth2ResourceServer(oauth2 -&gt; oauth2.jwt(Customizer.withDefaults()));<br>    return http.build();<br>}</pre><p>CSRF is disabled because this is a <strong>stateless</strong>, token-authenticated API: there is no session cookie for an attacker to ride, so the CSRF token would guard nothing. CORS is intentionally narrow:</p><pre>@Bean<br>CorsConfigurationSource corsConfigurationSource() {<br>    CorsConfiguration config = new CorsConfiguration();<br>    config.setAllowedOrigins(List.of(&quot;http://localhost:3000&quot;));<br>    config.setAllowedMethods(List.of(&quot;GET&quot;, &quot;OPTIONS&quot;));<br>    config.setAllowedHeaders(List.of(&quot;Authorization&quot;, &quot;Content-Type&quot;));<br><br>    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();<br>    source.registerCorsConfiguration(&quot;/**&quot;, config);<br>    return source;<br>}</pre><p>The custom <em>JwtDecoder</em> is where the audience check is bolted on. Spring’s default validator checks signature, issuer, and expiry. We delegate to it and add an <em>AudienceValidator</em>:</p><pre>@Bean<br>JwtDecoder jwtDecoder(<br>        @Value(&quot;${spring.security.oauth2.resourceserver.jwt.issuer-uri}&quot;) String issuerUri,<br>        @Value(&quot;${app.security.jwt.audience:nextjs-frontend}&quot;) String audience) {<br>    NimbusJwtDecoder decoder = NimbusJwtDecoder.withIssuerLocation(issuerUri).build();<br>    decoder.setJwtValidator(new DelegatingOAuth2TokenValidator&lt;&gt;(<br>        JwtValidators.createDefaultWithIssuer(issuerUri),<br>        new AudienceValidator(audience)));<br>    return decoder;<br>}</pre><p>By the time the <a href="https://github.com/hcussi/nextjs-springboot-keycloak-poc/blob/main/backend/src/main/java/com/poc/backend/web/HelloController.java">controller</a> runs, the token is fully validated. The endpoint just reads a claim:</p><pre>@GetMapping(&quot;/hello&quot;)<br>public String hello(@AuthenticationPrincipal Jwt jwt) {<br>    String username = jwt.getClaimAsString(&quot;preferred_username&quot;);<br>    return &quot;Hello World, &quot; + username;<br>}</pre><p>The result: no token or an invalid, expired, or wrong-audience token yields <em>401</em>; a good one yields <em>200 Hello World, testuser</em>.</p><h4>Next.js: the next-auth Configuration</h4><p>On the frontend, next-auth’s Keycloak provider drives the Authorization Code flow. The <a href="https://github.com/hcussi/nextjs-springboot-keycloak-poc/blob/main/frontend/src/lib/auth.ts">provider config</a> names the confidential client and pins the checks:</p><pre>KeycloakProvider({<br>  clientId: CLIENT_ID,<br>  clientSecret: CLIENT_SECRET,<br>  issuer: KEYCLOAK_ISSUER,<br>  // Send PKCE (S256) and state; Keycloak enforces PKCE on this client.<br>  checks: [&quot;pkce&quot;, &quot;state&quot;],<br>})</pre><p>The client secret comes from a <strong>server-only</strong> environment variable (not <em>NEXT_PUBLIC_</em>), so it stays in the Next.js server runtime. The route handler wires the provider into the App Router.<br>Two callbacks move the access token from Keycloak into the session. The <em>jwt</em> callback captures tokens on initial sign-in and, on later calls, refreshes the access token when it is about to expire; the <em>session</em> callback exposes the access token to the app:</p><pre>callbacks: {<br>  async jwt({ token, account }) {<br>    if (account) {<br>      token.accessToken = account.access_token;<br>      token.refreshToken = account.refresh_token;<br>      token.accessTokenExpires = account.expires_at<br>        ? account.expires_at * 1000<br>        : Date.now() + 300 * 1000;<br>      return token;<br>    }<br>    // Still valid (refresh 10s early to avoid edge races).<br>    if (token.accessTokenExpires &amp;&amp; Date.now() &lt; token.accessTokenExpires - 10_000) {<br>      return token;<br>    }<br>    return refreshAccessToken(token);<br>  },<br>  async session({ session, token }) {<br>    session.accessToken = token.accessToken;<br>    session.error = token.error;<br>    return session;<br>  },</pre><p>The refresh itself is a direct call to Keycloak’s token endpoint with <em>grant_type=refresh_token</em>:</p><pre>const response = await fetch(`${KEYCLOAK_ISSUER}/protocol/openid-connect/token`, {<br>  method: &quot;POST&quot;,<br>  headers: { &quot;Content-Type&quot;: &quot;application/x-www-form-urlencoded&quot; },<br>  body: new URLSearchParams({<br>    client_id: CLIENT_ID,<br>    client_secret: CLIENT_SECRET,<br>    grant_type: &quot;refresh_token&quot;,<br>    refresh_token: token.refreshToken,<br>  }),<br>});</pre><p>Because refresh tokens are single-use in the realm, Keycloak returns a fresh refresh token each time, and the callback stores it. <br><strong>A crucial detail</strong>: the access token lives in the next-auth session <strong>in memory</strong>, never in <em>localStorage</em>, which keeps it out of reach of <strong>XSS-style token</strong> theft.</p><p>With a session in place, the page auto-calls the protected endpoint, attaching the access token as a Bearer header:</p><pre>fetch(`${API_URL}/hello`, {<br>  headers: { Authorization: `Bearer ${accessToken}` },<br>});</pre><p>Logout is a <strong>back-channel</strong> call so signing out of the app also ends the Keycloak SSO session, meaning the next login truly requires credentials again:</p><pre>events: {<br>  async signOut({ token }) {<br>    if (!token?.refreshToken) return;<br>    await fetch(`${KEYCLOAK_ISSUER}/protocol/openid-connect/logout`, {<br>      method: &quot;POST&quot;,<br>      headers: { &quot;Content-Type&quot;: &quot;application/x-www-form-urlencoded&quot; },<br>      body: new URLSearchParams({<br>        client_id: CLIENT_ID,<br>        client_secret: CLIENT_SECRET,<br>        refresh_token: token.refreshToken,<br>      }),<br>    });<br>  },<br>}</pre><h4>The Integration Detail That Makes It All Work: One Issuer</h4><p>Here is the seam that quietly breaks most first attempts. A JWT’s <em>iss</em> claim is a fixed string baked in by whoever minted the token. Both the browser (<em>which redirects to Keycloak and reads the discovery document</em>) and the backend (<em>which fetches the JWKS to verify signatures</em>) must reach Keycloak at a URL that matches that <em>iss</em> string <strong>exactly</strong>. But those two clients live in different places: the browser is on the host, the backend is inside the Docker network.</p><p>Keycloak is <a href="https://github.com/hcussi/nextjs-springboot-keycloak-poc/blob/main/docker-compose.yml#L16">pinned</a> to a single hostname:</p><pre>environment:<br>  KC_HTTP_PORT: 8081<br>  KC_HOSTNAME: http://keycloak:8081<br>  KC_HOSTNAME_STRICT: &quot;false&quot;</pre><p>So every token carries <em>iss: </em><a href="http://keycloak:8081/realms/web."><em>http://keycloak:8081/realms/web</em>.</a><br>- The <strong>backend</strong>, inside the Docker network, resolves <em>keycloak</em> natively by service name. Done.<br>- The <strong>browser</strong>, on the host, resolves <em>keycloak</em> only if you add one line to <em>/etc/hosts</em>:</p><pre>127.0.0.1 keycloak</pre><p>With that entry, <em>http://keycloak:8081</em> in the browser hits the published port, and the issuer is identical for discovery, JWKS, redirects, and validation. It is a one-time developer setup step, and it is the single most common point of failure in this whole integration.</p><h4>Bringing It Up</h4><p>Docker Compose runs all three services on a shared network, with health checks so startup is ordered: Keycloak becomes healthy (realm imported) before the backend, and both before the frontend.</p><pre>docker compose up -d --build</pre><p>Then, with the <em>/etc/hosts</em> entry in place, open <em>http://localhost:3000</em>, click <strong>Log in</strong>, sign in as <em>testuser</em> / <em>password</em>, and the home screen shows <strong>”Hello World, testuser”</strong>, fetched from the backend with a validated JWT.<br>Tracing one request end to end ties every section together:<br>1. <strong>Browser → Keycloak</strong> <em>/authorize</em> with PKCE <em>code_challenge</em> and <em>state</em>.<br>2. <strong>User authenticates</strong>; Keycloak redirects back with a one-time <em>code</em>.<br>3. <strong>Next.js server → Keycloak</strong> <em>/token</em>: exchanges <em>code</em> + <em>code_verifier</em> + <em>client secret</em> for an access token, ID token, and refresh token.<br>4. <strong>Browser → Spring Boot</strong> <em>GET /hello</em> with <em>Authorization: Bearer &lt;access token&gt;.</em><br>5. <strong>Spring Boot</strong> validates signature (JWKS), issuer, expiry, and audience, then reads <em>preferred_username</em>.<br>6.<em> </em><strong><em>200 Hello World, testuser</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9v7LibVHnn_FaCp_Q_LcaA.png" /></figure><h4>Wrapping Up</h4><p>There is very little novel code here. What makes the integration work is getting a handful of settings to agree across three services: a confidential client running the Authorization Code flow with PKCE, a short-lived JWT carrying the right <em>iss</em> and <em>aud</em>, a resource server that checks both, and a single issuer URL that the browser and the backend can each resolve.</p><p>If you want to see it running, clone the repository, add the one <em>/etc/hosts </em>line, run <em>docker compose up</em>, and step through the flow yourself. The realm export, the Spring Security config, and the next-auth setup are all in the repo, ready to adapt to your own stack.</p><p>Continue in <a href="https://medium.com/@hernncussi/step-up-authentication-with-keycloak-spring-boot-and-next-js-9f4237009100">Part 3</a> with step-up authentication.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d2af701a248" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an OAuth2 POC with an AI Coding Agent]]></title>
            <link>https://medium.com/@hernncussi/building-an-oauth2-poc-with-an-ai-coding-agent-a80addd933da?source=rss-82e8d590697f------2</link>
            <guid isPermaLink="false">https://medium.com/p/a80addd933da</guid>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[keycloak]]></category>
            <category><![CDATA[oauth2]]></category>
            <category><![CDATA[nextauthjs]]></category>
            <category><![CDATA[authorization-code]]></category>
            <dc:creator><![CDATA[Hernán Cussi]]></dc:creator>
            <pubDate>Wed, 01 Jul 2026 00:46:16 GMT</pubDate>
            <atom:updated>2026-07-01T17:59:29.347Z</atom:updated>
            <content:encoded><![CDATA[<h4>From PRD to Running Stack</h4><blockquote>What does it look like when you treat an AI coding agent less like an autocomplete and more like a developer who reads the spec first? This is the story of a small but complete Keycloak integration, and the workflow that produced it.</blockquote><p>What does it take to wire a Next.js frontend, a Spring Boot backend, and Keycloak into a working OAuth2 / OpenID Connect login, end to end, runnable with a single command? On paper it is a well-trodden pattern. In practice it is a minefield of issuer mismatches, CORS rules, token lifetimes, and a stack that, in this case, was newer than most of the training data the AI had ever seen.</p><p>I built <a href="https://github.com/hcussi/nextjs-springboot-keycloak-poc">this as a proof of concept</a>, but the interesting part is not the auth flow itself. It is the way it was built: a document-first workflow with an AI coding agent (Claude Code) where the requirements, the plan, and the project’s own operating manual were treated as first-class artifacts, committed to the repo before and alongside the code. This post is a transparent look at that process.</p><h4>The Proof of Concept: A Single Protected “Hello”</h4><p>The goal was deliberately small so the integration could be the star. A user opens the Next.js app, clicks <strong>Log in</strong>, authenticates against Keycloak, returns with a JWT, and the app calls one protected backend endpoint that validates the token and greets the user by name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0eXaZPqGy1Jil6abKvx6HQ.png" /><figcaption>Login flow</figcaption></figure><p>The stack:<br>- <strong>Frontend</strong>: Next.js 16 (App Router, TypeScript), next-auth v4 with the Keycloak provider, Tailwind CSS.<br>- <strong>Backend</strong>: Spring Boot 4 on Java 25, Gradle 9, configured as an OAuth2 Resource Server.<br>- <strong>Identity</strong>: Keycloak 26, importing a pre-configured `web` realm on startup.<br>- <strong>Orchestration</strong>: Docker Compose, health-gated so the services come up in order.<br>One command brings the whole thing to life:</p><pre>docker compose up -d --build</pre><h4>The AI Workflow: Documents First, Code Second</h4><p>This is the part worth slowing down for. The temptation with an AI coding agent is to type <strong>“build me a Keycloak login”</strong> and accept whatever comes out. I did the opposite. Every phase of the project produced an artifact that the AI then had to honor.</p><ol><li><strong>The PRD came before anything else</strong><br>The first deliverable was not code, it was a <a href="https://github.com/hcussi/nextjs-springboot-keycloak-poc/blob/main/PRD.md"><strong>PRD.md</strong></a>: a product requirements document. It defined the goals, the explicit non-goals, the components and their ports, numbered functional requirements (FR-K1 through FR-I3), non-functional requirements, and a set of acceptance criteria the finished POC would be measured against.<br>Crucially, it also recorded <strong>resolved decisions</strong> with their rationale.</li><li><strong>The PLAN turned requirements into an ordered build<br></strong>Once the PRD was approved, the AI produced <a href="https://github.com/hcussi/nextjs-springboot-keycloak-poc/blob/main/PLAN.md"><strong>PLAN.md</strong></a>: a concrete, ordered implementation guide. It proposed the repository layout, dedicated an entire section to the issuer / hostname strategy, and broke the work into four incremental, independently verifiable steps. Each step ended with an explicit <strong>Verify</strong> block. Nothing was built speculatively.</li><li><strong>The git history shows the plan executing<br></strong>Because the work was planned in steps, the <a href="https://github.com/hcussi/nextjs-springboot-keycloak-poc/commits/main/">commit history</a> reads like a table of contents rather than a pile of <em>wip</em> commits.</li><li><strong>CLAUDE.md: giving the agent a memory<br></strong>Here is where the workflow gets genuinely useful for a stack this new. <a href="https://github.com/hcussi/nextjs-springboot-keycloak-poc/blob/main/CLAUDE.md"><strong>CLAUDE.md</strong></a> is the project’s operating manual <em>for the AI</em>. It is checked into the repo and read automatically at the start of every session, so hard-won knowledge does not evaporate between conversations. It captures the commands, the architecture decisions, and, most valuably, the <strong>version gotchas</strong> where this stack diverges from what any model trained a year ago would assume.</li><li><strong>A custom subagent for the security pass</strong><br>Once the POC was feature-complete, I did not ask the same general-purpose session to <em>check the security</em>. I created a dedicated, read-only <strong><em>security-reviewer</em></strong> subagent, defined as a small Markdown file in <a href="https://github.com/hcussi/nextjs-springboot-keycloak-poc/blob/main/.claude/agents/security-reviewer.md">.claude/agents/</a>. The result after executed: <em>audience validation so a token minted for another client is rejected, PKCE enforced on both sides, single-use refresh tokens, least-privilege scopes, and full back-channel logout</em>. All surfaced by an agent reviewing its own team’s work.</li><li>Skills and tooling along the way<br>Beyond the subagent, the workflow leaned on Claude Code’s built-in skills as reusable, purpose-built tools rather than ad-hoc prompts: a <strong>changelog generator</strong> that turned the commit history into the human-readable <a href="https://github.com/hcussi/nextjs-springboot-keycloak-poc/blob/main/CHANGELOG.md">CHANGELOG.md</a>, a <strong>code-review</strong> pass over the working diff, and a permissions allowlist (<em>.claude/settings.local.json</em>). The agent also wrote two helper scripts, <a href="https://github.com/hcussi/nextjs-springboot-keycloak-poc/blob/main/scripts/auth-code-flow.mjs"><em>auth-code-flow.mjs</em></a> and <a href="https://github.com/hcussi/nextjs-springboot-keycloak-poc/blob/main/scripts/e2e-login.mjs"><em>e2e-login.mjs</em></a>, the latter a headless smoke test of the entire login-to-”<strong>/hello</strong>” loop, used to verify each step.</li></ol><h4>The Indispensable Human Element</h4><p>It would be easy to read the above as “<em>the AI did everything.</em>” It did not, and that is the point. The AI was an extraordinarily fast and well-read developer, but the <strong>direction</strong> came from a human at every gate.</p><p>I decided that the POC should be one protected endpoint and not a sprawling app. I made the call to keep the Keycloak client confidential rather than a public SPA. I approved the <strong>PRD</strong> and the <strong>PLAN</strong> before any code was written, and I reviewed each step before it was committed. The agent accelerated the <strong>how</strong>; the <strong>what</strong> and the <strong>why</strong> stayed with me.</p><h4>Beyond a Single Project: A Reproducible Way to Build</h4><p>The auth flow in this repo is replaceable. The workflow is the durable asset.</p><p>A <strong>PRD</strong> that pins decisions, a <strong>PLAN</strong> that orders verifiable steps, a <strong>CLAUDE.md</strong> that remembers the stack’s sharp edges, and a purpose-built review subagent: these are not specific to <strong>Keycloak</strong>. They are a template for building almost anything with an AI agent in a way that stays reviewable, reproducible, and honest about what is a proof of concept versus what is production-ready.</p><h4>Try It Yourself</h4><p>If you want to see the whole thing, <a href="https://github.com/hcussi/nextjs-springboot-keycloak-poc">clone the repository</a>, add the one <em>/etc/hosts</em> line, run <em>docker compose up</em>, and watch a stranger become “<strong>Hello World, testuser</strong>” with a validated JWT. Then read the <a href="https://github.com/hcussi/nextjs-springboot-keycloak-poc/blob/main/PRD.md"><strong>PRD.md</strong></a>, <a href="https://github.com/hcussi/nextjs-springboot-keycloak-poc/blob/main/PLAN.md"><strong>PLAN.md</strong></a>, and <a href="https://github.com/hcussi/nextjs-springboot-keycloak-poc/blob/main/CLAUDE.md"><strong>CLAUDE.md</strong></a> side by side with the commit history. That, more than any single file, is the project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x4TxMCt7kzTtFZfHDhD2fA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s8tFJyQfKEmr5cfIeFUfpA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jgSEwZzxiWO555UAfsBCoQ.png" /><figcaption>Login flow</figcaption></figure><h4>Part 1 of a series</h4><p>This post is about how the proof of concept got built: a document-first workflow with an AI coding agent, and what that process looked like. It deliberately stays out of the code. If you want the technical deep dive, the <a href="https://medium.com/@hernncussi/wiring-next-js-spring-boot-and-keycloak-with-the-oauth2-authorization-code-flow-7d2af701a248">second post</a> walks through the OAuth2 Authorization Code flow with PKCE, the Keycloak realm, the Spring Boot resource server, and the next-auth setup across all three services.</p><p><em>This proof of concept was built collaboratively with Claude Code (Anthropic’s CLI coding agent), and this post documents that workflow.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a80addd933da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Prompt to Product: The Story of an AI-Built Chat Application]]></title>
            <link>https://medium.com/@hernncussi/from-prompt-to-product-the-story-of-an-ai-built-chat-application-47639ca1b1e0?source=rss-82e8d590697f------2</link>
            <guid isPermaLink="false">https://medium.com/p/47639ca1b1e0</guid>
            <category><![CDATA[prompt-engineering]]></category>
            <dc:creator><![CDATA[Hernán Cussi]]></dc:creator>
            <pubDate>Wed, 31 Dec 2025 16:32:19 GMT</pubDate>
            <atom:updated>2026-07-06T14:24:55.303Z</atom:updated>
            <content:encoded><![CDATA[<p>What does it look like when a large language model builds a complete web application from scratch? This <a href="https://github.com/hcussi/chat-ai">project</a>, a feature-rich chat interface for the Google Gemini API, serves as a fascinating case study. From the initial prompt to the final deployment-ready code, the entire development process was handled by Gemini, an AI assistant. This article chronicles that journey, offering a transparent look into the iterative, and surprisingly human, process of AI-powered software development.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AIUF8tmazjJKSQLZqq2UqQ.png" /></figure><h4>The Proof of Concept: A Simple Chat App</h4><p>The <a href="https://github.com/hcussi/chat-ai">project</a> began with a simple goal: <em>create a web-based chat application that could interact with the Google Gemini API</em>.</p><p>The initial requirements, outlined in a <a href="https://github.com/hcussi/chat-ai/blob/main/prompt.md">prompt.md</a> file, were straightforward. The AI’s first task was to create a plan, which evolved based on feedback to include modern development practices like unit testing and version control for each significant step.</p><p>The core technologies chosen were:<br>- <strong>Framework</strong>: Next.js 13.4<br>- <strong>Language</strong>: JavaScript<br>- <strong>Styling</strong>: Tailwind CSS<br>- <strong>API</strong>: Google Generative AI (<em>@google/generative-ai</em>)<br>- <strong>Testing</strong>: Jest and React Testing Library</p><h4>The Development Journey: An Iterative Process</h4><p>The AI’s development process, meticulously logged in <a href="https://github.com/hcussi/chat-ai/blob/main/GEMINI.md">GEMINI.md</a>, was not a linear path but a series of steps involving scaffolding, implementation, debugging, and constant refinement based on user feedback.</p><ol><li><strong>Scaffolding and Setup</strong></li></ol><p>The AI initiated the project using <em>create-next-app</em>. It immediately faced and solved real-world development hurdles. For instance, it navigated an interactive CLI prompt for TypeScript by consulting the help manual and using the<em> javascript</em> flag. It then methodically installed production and development dependencies and configured the Jest testing environment.</p><p>2. <strong>Building the Core</strong></p><p>With the foundation in place, the AI implemented the core features. It first built the backend API route (<em>app/api/chat/route.js</em>) to handle communication with the Gemini API. Following that, it constructed the frontend UI in a single <em>app/page.js</em> file and applied a clean, modern theme with Tailwind CSS. Crucially, it also wrote the corresponding unit tests, adhering to the project’s quality standards.</p><p>3. <strong>Debugging and Refinement: The Real Work</strong></p><p>This phase showcased the AI’s problem-solving capabilities. It tackled several bugs that would be familiar to any developer:<br>- A <em>PostCSS configuration issue</em> preventing the app from starting was resolved by installing the correct package.<br>- A <em>404 error from the Gemini API</em> was traced to an incorrect model name (<em>gemini-pro</em>). The AI used web search to find the correct, available model (<em>gemini-1.5-flash</em>) and fixed the API call. It then refactored the hardcoded model name into an environment variable for better configuration.<br>- A <em>port conflict</em> caused a cryptic rendering error. The AI diagnosed this by using <em>lsof -i :3000</em> to find and terminate a zombie Node.js process.</p><p>4. <strong>Evolving the User Experience</strong></p><p>As the core functionality stabilized, development shifted towards enhancing the UI and UX. Based on a series of requests, the AI:<br>- Implemented “Enter to send” and “Shift+Enter for newline” functionality.<br>- Changed the theme to a futuristic, light-blue style with a custom font and background image.<br>- Restructured the layout multiple times, moving from a single view to a three-column layout and back again, demonstrating flexibility in adapting to changing requirements.<br>- Integrated the <em>showdown</em> library to render the API’s Markdown responses as formatted HTML.<br>- Added a status bar with usage statistics persisted in <em>localStorage</em>.</p><p>5. <strong>Refactoring for Maintainability</strong></p><p>As the main page component grew complex, the AI was tasked with refactoring it. It broke the monolithic UI into smaller, manageable components (<em>ChatManager</em>, <em>History</em>, <em>Input</em>, <em>Loading</em>), each with its own dedicated test file. This critical step improved the codebase’s modularity and maintainability.</p><p>6. <strong>Advanced Feature Implementation</strong></p><p>With a solid architecture, the AI added sophisticated features:<br>- <strong>Multi-Chat Management</strong>: It built a system to handle multiple, distinct chat sessions. Users could create new chats, rename them, and delete them, with validation to prevent duplicate names or the deletion of the last remaining chat.<br>- <strong>Stateful UI</strong>: A distinct style was added to indicate the currently selected chat, improving usability.</p><h4>Final State: A Fully Functional Application</h4><p>The result of this AI-driven process is a complete and functional application. It serves as a powerful demonstration of how LLMs can be used not just for code completion, but to manage an entire development lifecycle. The repository, with its detailed logs and documents (<a href="https://github.com/hcussi/chat-ai/blob/main/plan.md">plan.md</a>, <a href="https://github.com/hcussi/chat-ai/blob/main/PRD.md">PRD.md</a>, and <a href="https://github.com/hcussi/chat-ai/blob/main/GEMINI.md">GEMINI.md</a>), stands as a testament to this new paradigm of software creation.</p><h4>The Indispensable Human Element</h4><p>While this project showcases the remarkable capabilities of AI in software development, it also underscores the enduring and critical role of human oversight. The AI, in this context, acted as an incredibly efficient and versatile developer, but it was guided by precise human input. Key areas where human involvement remained indispensable include:<br>- <strong>Initial Specification and Prompt Engineering</strong>: The clarity and completeness of the initial <a href="https://github.com/hcussi/chat-ai/blob/main/prompt.md">prompt.md</a> and subsequent iterative feedback were crucial. Humans are responsible for defining the problem, setting the vision, and articulating requirements in a way that AI can interpret and act upon.<br>- <strong>Review and Quality Assurance</strong>: Despite the AI’s ability to generate code and tests, human developers are essential for reviewing the generated code, ensuring it meets architectural standards, identifying potential edge cases, and verifying the overall quality and security of the application.<br>- <strong>Strategic Guidance and Course Correction</strong>: The project’s evolution involved numerous adjustments, theme changes, and refactors based on user feedback. This strategic direction, the decision-making on <strong><em>what</em></strong> to build next or <strong><em>how</em></strong> to pivot, remains a human domain.<br>- <strong>Debugging Complex Issues</strong>: While the AI demonstrated impressive debugging skills for certain issues, particularly those related to configuration and API usage, highly abstract or deeply architectural bugs often require human intuition and understanding of broader system context.</p><p>In essence, AI accelerates the <strong><em>how</em></strong>, but humans continue to define the <strong><em>what</em></strong> and <strong><em>why</em></strong>, ensuring that the technology serves meaningful and well-aligned objectives.</p><h4>Beyond a Single Project: Reproducible AI Development</h4><p>A key takeaway from this experiment is the creation of high-quality documentation as a byproduct of the development process. The <a href="https://github.com/hcussi/chat-ai/blob/main/plan.md">plan.md</a> and <a href="https://github.com/hcussi/chat-ai/blob/main/PRD.md">PRD.md</a> files are not just historical artifacts; they are detailed, structured blueprints. These documents could be fed into another LLM, potentially allowing for the rapid and consistent recreation or iteration of this application. This opens up exciting possibilities for reproducible, scalable, and transferable AI-driven software development.</p><h4>Improving the UI design (2026/07/06)</h4><p>After <strong>6 months</strong> I had some time to come back to this and improve the UI, to see how I did it <a href="https://medium.com/@hernncussi/redesigning-an-ai-built-ui-with-a-claude-code-agent-and-a-skill-032cb9cb3dd6">check this</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_N4txs1RKnR2hl2Nd9q-FA.png" /></figure><p><strong>Note</strong>: <em>This post was improved and powered using the Gemini LLM.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47639ca1b1e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Java 21 Features: A Deep Dive into Performance and Concurrency]]></title>
            <link>https://medium.com/@hernncussi/exploring-java-21-features-a-deep-dive-into-performance-and-concurrency-2bc0a37b2669?source=rss-82e8d590697f------2</link>
            <guid isPermaLink="false">https://medium.com/p/2bc0a37b2669</guid>
            <category><![CDATA[java-21-features]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[virtual-threads]]></category>
            <category><![CDATA[gatling]]></category>
            <dc:creator><![CDATA[Hernán Cussi]]></dc:creator>
            <pubDate>Wed, 31 Dec 2025 15:51:42 GMT</pubDate>
            <atom:updated>2025-12-31T15:51:42.929Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Java 21 has been with us for some time now, and while this might be a late review, it’s still worth exploring the different possibilities it offers.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*juzbOReJyH4n01cwDcKq_A.png" /></figure><p>It’s packed with new features that promise to change the way we write concurrent and performant applications. In this post, we’ll explore some of these new features in a hands-on way. We’ll use a Spring Boot application to test the performance of these new features, record metrics, and compare the results. We’ll look at:</p><ul><li><strong>Java 21’s new features</strong>: We’ll see how anonymous variables, string templates, and virtual threads with structured subtasks are used in a real-world application.</li><li><strong>Caching strategies</strong>: We’ll compare the performance of in-memory caching with <em>EhCache</em> and a distributed cache with <em>Redis</em>.</li><li><strong>Concurrency models</strong>: We’ll look at the difference between traditional platform threads and the new virtual threads.</li></ul><p>So, let’s dive in and see what Java 21 has to offer!</p><p>The github repo is <a href="https://github.com/hcussi/metrics-concurrency">https://github.com/hcussi/metrics-concurrency</a>.</p><h4>Virtual Threads and Structured Concurrency</h4><p>One of the most exciting features in Java 21 is the introduction of virtual threads and structured concurrency. Virtual threads are a lightweight implementation of threads that are managed by the Java Virtual Machine (JVM) rather than the operating system. This allows for a massive number of concurrent tasks without the overhead of creating new OS threads.<br>Structured concurrency simplifies concurrent programming by treating multiple tasks running in different threads as a single unit of work. This makes it easier to manage and cancel concurrent tasks.<br>In our project, we use a <em>StructuredTaskScope</em> to calculate factorials and squares of a list of numbers concurrently. Each number is processed in its own virtual thread, and the <em>StructuredTaskScope</em> ensures that all tasks are completed or that they are all cancelled if one of them fails.<br>Here’s the code from <em>src/main/java/com/hernancussi/poc/metrics/concurrency/business/MathBusinessService.java</em>:</p><pre>protected Map&lt;Integer, BigInteger&gt; calculateVirtual(List&lt;Integer&gt; numbers, MathematicalOperation mathematicalOperation) throws InterruptedException, ExecutionException {<br><br>    try(var scope = new StructuredTaskScope.ShutdownOnFailure()) {<br><br>      var tasks = numbers.stream().map(number -&gt; new MathematicalTask(number, mathematicalOperation)).toList();<br><br>      var subtasks = tasks.stream().map(scope::fork).toList();<br><br>      // Wait till all tasks succeed or first Child Task fails.<br>      // Send cancellation to all other Child Tasks if one fails<br>      scope.join();<br>      scope.throwIfFailed();<br><br>      return subtasks.stream()<br>        .map(StructuredTaskScope.Subtask::get)<br>        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));<br>    }<br>  }</pre><h4>String Templates</h4><p>String templates are another new feature in Java 21 that aims to make string manipulation more readable and concise. They allow you to embed expressions directly into a string, which are then evaluated and interpolated at runtime.<br>In our project, we use string templates for logging and creating cache keys. For example, in <em>src/main/java/com/hernancussi/poc/metrics/concurrency/aop/HandleRestRequestAspect.java</em>, we use a string template to log the name of the REST method that is being called:</p><pre>log.info(STR.&quot;REST method: \{joinPoint.getSignature().getName()}&quot; + (hasArgs ? STR.&quot; called with: \{joinPoint.getArgs()[0]}&quot; : &quot;&quot;));</pre><p>And in <em>src/main/java/com/hernancussi/poc/metrics/concurrency/cache/RedisCacheService.java</em>, we use a string template to create a key for the Redis cache:</p><pre>return redisTemplate.opsForValue().get(STR.&quot;\{this.namespace}:\{key}&quot;);</pre><p>These examples show how string templates can make the code more readable by avoiding the need for string concatenation.</p><h4>Anonymous Variables</h4><p>Anonymous variables are a small but useful new feature in Java 21. They allow you to use an underscore <em>_</em> as a placeholder for a variable that is not used. This can be useful in lambda expressions and try-with-resources statements, where you are forced to declare a variable that you don’t need.<br>In our project, we use anonymous variables in a lambda expression in <em>src/main/java/com/hernancussi/poc/metrics/concurrency/aop/LoggerAspect.java</em>:</p><pre>return LOGGER_MAP.computeIfAbsent(clazz, (_) -&gt; LoggerFactory.getLogger(clazz));</pre><p>Here, the underscore _ is used as a placeholder for the key of the map, which is not used in the lambda expression.</p><h4>Performance Comparison: Caching</h4><p>Caching is a crucial technique for improving the performance of any application, especially for computationally expensive operations. In our project, calculating factorials for large numbers can be resource-intensive. By caching the results, we can avoid re-computing them for the same input, leading to significantly faster response times for repeated requests.</p><p>The project uses Spring AOP (Aspect-Oriented Programming) to handle caching in a clean and decoupled way. The core logic is in the <em>HandleCacheMathAspect</em> class. This aspect intercepts calls to the mathematical calculation methods (like <em>FactorialProvider.apply</em> and <em>SquareProvider.apply</em>).</p><p>Here’s the flow:<br>1. When a calculation is requested, the aspect’s <em>aroundMath</em> method is triggered first.<br>2. It checks if the result for the given number already exists in the configured cache (<em>EhCache</em> or <em>Redis</em>).<br>3. If a cached value is found, it’s returned immediately, and the actual calculation method is never called.<br>4. If the value is not in the cache, the calculation proceeds, and the aspect stores the new result in the cache before returning it.</p><p>This AOP-based approach is powerful because it adds caching functionality without cluttering the core business logic of the mathematical calculations.</p><p>You can switch between the following caching strategies by activating the corresponding Spring profile.</p><h4>EhCache</h4><p>To use EhCache, you need to run the application with the <em>ehcache</em> profile:</p><pre>./gradlew bootRun - args=&#39; - spring.profiles.active=ehcache&#39;</pre><p>This will activate the configuration in <em>src/main/resources/application-ehcache.properties</em>, which sets the cache strategy to <em>EHCACHE</em>.</p><h4>Redis</h4><p>To use Redis, you need to run the application with the `redis` profile:</p><pre>./gradlew bootRun --args=&#39;--spring.profiles.active=redis&#39;</pre><p>This will activate the configuration in <em>src/main/resources/application-redis.properties</em>, which sets the cache strategy to <em>REDIS</em>. Note that you also need to have a Redis instance running. You can start one using the <em>docker-compose-concurrency.yml</em> file provided in the project.</p><h4>Performance Testing</h4><p>Before running the performance tests, you’ll need a valid JWT token (read the complete guide how to set up <a href="https://github.com/hcussi/metrics-concurrency/tree/master?tab=readme-ov-file#getting-started">here</a>). The first step is to generate a secret key and add it to your <em>.env</em> file. You can do this by calling the <em>/api/v1/generateSecret</em> endpoint:</p><pre>$docker-compose -f docker-compose-concurrency.yml up -d<br>$curl http://localhost:8080/api/v1/generateSecret</pre><p>Once you have the secret key in your <em>.env</em> file, you can obtain a JWT token by calling the authentication endpoint with your credentials (also defined in the <em>.env</em> file):</p><pre>$curl  -d &#39;{&quot;username&quot;: MY_API_USERNAME, &quot;password&quot;: MY_API_PASSWORD}&#39; -H &quot;Content-Type: application/json&quot; http://localhost:8080/api/v1/authentication</pre><p>The project includes Gatling tests that can be used to compare the performance of the different caching and concurrency strategies. You can find the test simulation in <em>src/gatling/java/com/hernancussi/poc/metrics/concurrency/simulations/MathRegistrationSimulation.java</em>.</p><p>To run the tests, you need to execute the following command with the JWT token you just generated:</p><pre>./gradlew gatlingRun -DGATLING_TOKEN=My_JWT_Token</pre><p>After the tests have finished, you can find the performance reports in the <em>build/reports/gatling</em> directory. Check the last section <strong>Interpreting the Gatling Report</strong>.</p><h4>Performance Comparison: Concurrency</h4><p>Java 21’s virtual threads promise to revolutionize concurrent programming in Java. Our project allows you to compare the performance of virtual threads with traditional platform threads.</p><p>You can switch between these concurrency strategies by using the <em>strategy</em> query parameter in the REST API.</p><p>To use platform threads, you need to set the <em>strategy</em> query parameter to <em>THREADS</em>:</p><pre>/api/v1/calculateFactorial?strategy=THREADS</pre><p>This will execute the <em>calculateThreads</em> method in <em>src/main/java/com/hernancussi/poc/metrics/concurrency/business/MathBusinessService.java</em>, which uses a fixed thread pool to run the tasks concurrently:</p><pre>public Map&lt;Integer, BigInteger&gt; calculateThreads(List&lt;Integer&gt; numbers, int fixedPoolSize, MathematicalOperation mathematicalOperation) throws InterruptedException {<br><br>    // On heavy load might produce java.lang.OutOfMemoryError: unable to create native thread: possibly out of memory or process/resource limits reached<br>    try(var executorService = Executors.newFixedThreadPool(fixedPoolSize)) {<br>      var tasks = numbers.stream().map(number -&gt; new MathematicalTask(number, mathematicalOperation)).toList();<br><br>      var futures = executorService.invokeAll(tasks);<br><br>      return futures.stream()<br>        .map(entryFuture -&gt; {<br>          try {<br>            return entryFuture.get();<br>          } catch (InterruptedException | ExecutionException e) {<br>            throw new RuntimeException(e);<br>          }<br>        })<br>        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));<br>    }<br>  }</pre><h4>Virtual Threads</h4><p>To use virtual threads, you need to set the <em>strategy</em> query parameter to <em>VIRTUAL</em>:</p><pre>/api/v1/calculateFactorial?strategy=VIRTUAL</pre><p>This will execute the <em>calculateVirtual</em> method in <em>src/main/java/com/hernancussi/poc/metrics/concurrency/business/MathBusinessService.java</em>, which uses a <em>StructuredTaskScope</em> to run the tasks concurrently in virtual threads.</p><h4>Conclusion</h4><p>Java 21 brings a host of new features that can help you write more performant and concurrent applications. In this post, we’ve seen how to use some of these features in a real-world Spring Boot application. We’ve also seen how to compare the performance of different caching and concurrency strategies using Gatling tests.</p><p>The introduction of virtual threads and structured concurrency is a game-changer for concurrent programming in Java. It allows you to write highly concurrent applications without the complexity of traditional thread management.</p><p>String templates and anonymous variables are smaller features, but they can help to make your code more readable and concise.</p><p>So, what are you waiting for? Go ahead and try out these new features in your own projects!</p><h3>Interpreting the Gatling Report</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qF6YiTf3dX2MdOFlxjSJEQ.png" /></figure><p>After running the Gatling tests, you’ll find a detailed HTML report in the <em>build/reports/gatling</em> directory. This report is essential for understanding the performance of your application under load. Here’s a guide to interpreting it.</p><h4>Key Statistics to Watch</h4><p>The report’s main page provides a table with key metrics for each request. Here’s what they mean:</p><ul><li><strong>Total Requests</strong>: The total number of times a request was sent.</li><li><strong>OK / KO</strong>: The number and percentage of successful (OK) and failed (KO) requests. A high KO percentage indicates problems.</li><li><strong>Min / Max</strong>: The fastest and slowest response times for a request.</li><li><strong>Mean</strong>: The average response time. While useful, it can be skewed by a few very slow or fast requests.</li><li><strong>Std Dev (Standard Deviation)</strong>: This shows how much the response times vary. A low number is good, indicating consistent performance.</li><li><strong>Percentiles (50th, 75th, 95th, 99th)</strong>: These are often the most important metrics. The 95th percentile (p95), for example, tells you that 95% of your users experienced a response time of that value or less. It’s a great way to understand the experience of the majority of your users, ignoring the extreme outliers.</li></ul><h4>Understanding the Graphs</h4><p>The report includes several charts that visualize the test run:</p><ul><li><strong>Active Users Over Time</strong>: Shows how the number of simulated users changed during the test.</li><li><strong>Response Time Distribution</strong>: This histogram shows the frequency of different response time ranges. It helps you visualize where most requests fall.</li><li><strong>Response Time Percentiles Over Time</strong>: This line graph is crucial. It shows how the percentiles (like p95) changed as the load test progressed. If the lines trend upwards, it indicates that performance degrades as the test continues, suggesting potential bottlenecks.</li><li><strong>Requests per Second</strong>: This shows the throughput of your application, which is a key measure of its capacity.</li></ul><h4>Breakdown of the Test Requests</h4><p>Based on the <em>MathRegistrationSimulation.java</em> file, the load test executes the following requests for each user. You can compare their performance in the “Details” tab of the report.</p><ul><li><em>factorial-request</em> and <em>square-request</em>: These use the default concurrency strategy, which is a simple, single-threaded calculation. They serve as a baseline to measure the improvements from other strategies.</li><li><em>factorial-virtual-request</em> and <em>square-virtual-request</em>: These requests use the <em>?strategy=VIRTUAL</em> parameter. When analyzing the report, you should expect these to have significantly better performance (lower response times and higher throughput) than the baseline, especially under load. This demonstrates the power of virtual threads for handling many concurrent tasks.</li><li><em>factorial-thread-request</em> and <em>square-thread-request</em>: These use the <em>?strategy=THREADS</em> parameter, leveraging traditional platform threads with a fixed thread pool. You should compare these to the virtual thread requests. For I/O-bound or numerous short-lived tasks, virtual threads will likely outperform platform threads. For CPU-bound tasks, the difference might be less pronounced, but virtual threads should still show benefits in resource management.</li></ul><p>By comparing the statistics and graphs for these different request types, you can draw clear conclusions about which caching and concurrency strategies work best for this application’s workload.</p><p><strong>Note</strong>: <em>This post was improved and powered using the Gemini LLM.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2bc0a37b2669" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Cloud Microservices POC]]></title>
            <link>https://medium.com/@hernncussi/spring-cloud-microservices-poc-1c3921eb2234?source=rss-82e8d590697f------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c3921eb2234</guid>
            <category><![CDATA[microservices-pattern]]></category>
            <category><![CDATA[spring-cloud]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Hernán Cussi]]></dc:creator>
            <pubDate>Mon, 29 Dec 2025 19:36:43 GMT</pubDate>
            <atom:updated>2025-12-29T19:43:14.517Z</atom:updated>
            <content:encoded><![CDATA[<h4>Deconstructing some Microservices Patterns</h4><p>Have you ever wanted to explore the complexities of a microservices architecture in a practical, hands-on environment? The Java Lyrics project is designed to do just that. While it presents as a feature-rich application for music lovers — allowing users to search for songs, artists, and albums, and ultimately retrieve lyrics — its primary purpose is a Proof of Concept (POC).</p><p>This project serves as an open-source sandbox for testing and demonstrating various Spring Cloud features and essential microservice patterns. Built with Java 21, Spring Boot 3, and Spring Cloud, it provides a comprehensive example of a sophisticated microservices ecosystem. It is <strong>not</strong> intended for production use, but rather as a robust learning tool. For a detailed setup guide and more information, refer to the project’s <a href="https://github.com/hcussi/java-lyrics/blob/master/README.md">README.md</a> file. This article dives into the practical application of these patterns by exploring the <a href="https://github.com/hcussi/java-lyrics">Java Lyrics project</a>. We’ll break down each key pattern, explain its purpose, and show how it’s implemented in the repository with real code snippets.</p><figure><img alt="Java Spring Cloud for the Java Lyrics Project" src="https://cdn-images-1.medium.com/max/1024/1*z2iKAKm7FWQXwQ3uIpv3Mw.png" /></figure><h4>The Architecture</h4><p>The Java Lyrics application is a monorepo containing several independent microservices that work together. Key components include a user service, a lyrics service, an API gateway, and a discovery server, all supported by a robust infrastructure for logging, tracing, and messaging.</p><p>Let’s explore the core patterns that make this architecture robust and efficient.</p><h4>API Gateway Pattern</h4><p><strong>Goal</strong>: To provide a single, unified entry point for all client requests, simplifying the client-side and protecting the internal microservices.</p><p><strong>Description</strong>: The API Gateway acts as a reverse proxy, routing incoming requests to the appropriate downstream service. It can also handle cross-cutting concerns like authentication, SSL termination, rate limiting, and response caching. This decouples clients from the internal service topology, which can change freely without affecting the end-user.</p><p><strong>Example in Java Lyrics</strong>: The <em>api-gateway-service</em> is a Spring Cloud Gateway application. It defines routes that map URL paths to specific microservices, like the user service or the lyrics service. It also integrates security and resilience patterns.</p><p><strong>Code Snippet</strong> (<em>api-gateway-service/src/main/resources/application.yml</em>):</p><pre>spring:<br>  cloud:<br>    gateway:<br>      routes:<br>        - id: user-service<br>          uri: lb://user-service<br>          predicates:<br>            - Path=/api/v1/users/**<br>          filters:<br>            - name: CircuitBreaker<br>              args:<br>                name: userServiceCircuitBreaker<br>                fallbackUri: forward:/fallback/user-service<br>            - Retry=3<br>        - id: lyrics-service<br>          uri: lb://lyrics-service<br>          predicates:<br>            - Path=/api/v1/lyrics/**<br>          filters:<br>            - name: CircuitBreaker<br>              args:<br>                name: lyricsServiceCircuitBreaker<br>                fallbackUri: forward:/fallback/lyrics-service<br>            - Retry=3</pre><p>Find the complete code <a href="https://github.com/hcussi/java-lyrics/tree/master/api-gateway-service">here</a></p><h4>Service Discovery Pattern</h4><p><strong>Goal</strong>: To allow services to find and communicate with each other dynamically without hardcoding hostnames and ports.</p><p><strong>Description</strong>: In a microservices environment, services are often scaled up and down, and their network locations can change. A Service Discovery server (like Netflix Eureka) acts as a registry. Each microservice registers itself with the server upon startup and sends periodic heartbeats. When one service needs to call another, it queries the registry to get the up-to-date location.</p><p><strong>Example in Java Lyrics</strong>: The <em>discovery-server</em> is a Spring Boot application with Netflix Eureka. All other microservices are configured as Eureka clients that register themselves with this server.</p><p><strong>Code Snippet</strong> (<em>discovery-server/src/main/java/com/lyrics/discovery/DiscoveryServerApplication.java</em>):</p><pre>package com.lyrics.discovery;<br><br>import org.springframework.boot.SpringApplication;<br>import org.springframework.boot.autoconfigure.SpringBootApplication;<br>import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;<br><br>@SpringBootApplication<br>@EnableEurekaServer<br>public class DiscoveryServerApplication {<br><br>    public static void main(String[] args) {<br>        SpringApplication.run(DiscoveryServerApplication.class, args);<br>    }<br><br>}</pre><p>Find the complete code <a href="https://github.com/hcussi/java-lyrics/tree/master/discovery-server">here</a></p><h4>Circuit Breaker Pattern</h4><p><strong>Goal</strong>: To prevent a network or service failure from cascading to other services.</p><p><strong>Description</strong>: When a microservice calls another service that is slow or unavailable, it can consume resources while waiting for a response, potentially causing a system-wide failure. The Circuit Breaker pattern wraps these calls in a proxy that monitors for failures. If the number of failures exceeds a threshold, the circuit “opens,” and all further calls fail immediately, without even trying to contact the failing service. After a timeout, the circuit goes into a “half-open” state to see if the downstream service has recovered.</p><p><strong>Example in Java Lyrics</strong>: The <em>lyrics-service</em> communicates with an external API via the <em>lyrics-client-service</em>. This communication is protected by a Circuit Breaker using Spring Cloud Circuit Breaker (with Resilience4j). If the external API fails, the breaker opens, and a fallback method is invoked.</p><p><strong>Code Snippet</strong> (<em>lyrics-service/src/main/java/com/lyrics/service/LyricsServiceImpl.java</em>):</p><pre>// Simplified example of a Circuit Breaker implementation<br>@Override<br>@CircuitBreaker(name = &quot;lyrics-client&quot;, fallbackMethod = &quot;fallback&quot;)<br>public Mono&lt;String&gt; findLyrics(String artist, String song) {<br>    // Logic to call the lyrics-client-service<br>    return lyricsClient.searchLyrics(artist, song);<br>}<br><br>// Fallback method<br>public Mono&lt;String&gt; fallback(String artist, String song, Throwable throwable) {<br>    // Return a default or cached response<br>    return Mono.just(&quot;No lyrics found at the moment. Please try again later.&quot;);<br>}</pre><p>Find the complete code <a href="https://github.com/hcussi/java-lyrics/tree/master/lyrics-service">here</a></p><h4>Asynchronous Event-Driven Communication</h4><p><strong>Goal</strong>: To decouple services and improve resilience by using a message broker for communication instead of direct synchronous calls.</p><p><strong>Description</strong>: Instead of waiting for a direct response, services can publish events to a message queue (like Apache Kafka). Other services can subscribe to these events and react to them asynchronously. This pattern is excellent for long-running processes or when you want to notify multiple services of a state change without creating tight coupling.</p><p><strong>Example in Java Lyrics</strong>: The <em>user-service</em> publishes an event to a Kafka topic whenever a new user registers. The <em>email-service</em> listens to this topic and sends a welcome email, all without the user service needing to know about the email service’s existence.</p><p><strong>Code Snippet</strong> (<em>email-service/src/main/java/com/lyrics/email/service/UserListener.java</em>):</p><pre>package com.lyrics.email.service;<br><br>import com.lyrics.email.events.UserRegisteredEvent;<br>import org.springframework.kafka.annotation.KafkaListener;<br>import org.springframework.stereotype.Component;<br><br>@Component<br>public class UserListener {<br><br>    @KafkaListener(topics = &quot;user-registered-topic&quot;)<br>    public void handleUserRegistration(UserRegisteredEvent event) {<br>        System.out.println(&quot;Received user registration event for email: &quot; + event.getEmail());<br>        // Add logic here to send a welcome email<br>    }<br>}</pre><p>Find the complete code <a href="https://github.com/hcussi/java-lyrics/tree/master/email-service">here</a></p><h4>Centralized Logging and Distributed Tracing</h4><p><strong>Goal</strong>: To aggregate logs from all microservices into a central location and to trace a single request as it flows through multiple services.</p><p><strong>Centralized Logging</strong>: Debugging is difficult when logs are scattered across dozens of service instances. The ELK Stack (Elasticsearch, Logstash, Kibana) provides a powerful solution. Services write logs in a structured format (JSON), Logstash collects and processes them, Elasticsearch indexes them for searching, and Kibana provides a web UI for visualization.<br><strong>Distributed Tracing</strong>: To understand the latency and behavior of a request, we need to trace its entire journey. Micrometer and Zipkin are used for this. A unique trace ID is added to the initial request and propagated to all subsequent service calls, allowing Zipkin to reconstruct the full sequence of events.</p><p><strong>Example in Java Lyrics</strong>: All services are configured to output JSON logs, which are shipped to Elasticsearch via Logstash. The project’s <em>docker-compose-lyrics-elk.yml</em> file defines the entire ELK stack. For tracing, each service includes the Micrometer Tracing dependency, and the <em>application.yml</em> is configured to send trace data to a Zipkin server.</p><p><strong>Code Snippet</strong> (Configuration for Tracing in <em>application.yml</em>):</p><pre>management:<br>  tracing:<br>    sampling:<br>      probability: 1.0 # Trace all requests<br><br>logging:<br>  pattern:<br>    level: &quot;%5p [${spring.application.name:},%X{traceId:-},%X{spanId:-}]&quot;</pre><p>Find the complete infrastructure setup <a href="https://github.com/hcussi/java-lyrics/blob/master/docker-compose-lyrics-elk.yml">here</a></p><h4>Conclusion</h4><p>The Java Lyrics project serves as an excellent blueprint for anyone looking to understand and implement a modern microservices architecture. By applying patterns like API Gateway, Service Discovery, Circuit Breaker, and event-driven communication, you can build systems that are not only scalable and flexible but also resilient to the failures inherent in distributed environments.</p><p>I encourage you to clone the repository, run the services using Docker Compose, and explore the code for yourself. Happy coding!</p><h4>References to Spring Cloud Documentation</h4><p>For a deeper dive into the Spring Cloud features used in this project, refer to the official documentation:</p><ul><li><a href="https://docs.spring.io/spring-cloud-gateway/docs/current/reference/html/">Spring Cloud Gateway</a></li><li><a href="https://docs.spring.io/spring-cloud-netflix/docs/current/reference/html/">Spring Cloud Netflix Eureka (Service Discovery)</a></li><li><a href="https://docs.spring.io/spring-cloud-circuitbreaker/docs/current/reference/html/">Spring Cloud CircuitBreaker (Resilience4j)</a></li><li><a href="https://docs.spring.io/spring-cloud-stream/docs/current/reference/html/">Spring Cloud Stream (Kafka)</a></li><li><a href="https://docs.spring.io/spring-boot/docs/current/reference/html/actuator.html">Spring Boot Actuator (Metrics and Tracing)</a></li><li><a href="https://docs.spring.io/spring-security/reference/servlet/oauth2/index.html">Spring Security (OAuth2)</a></li></ul><p><strong>Note</strong>: This post was improved and powered using the Gemini LLM.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c3921eb2234" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>