<?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"><channel><title><![CDATA[Spring/Java universe]]></title><description><![CDATA[Spring/Java universe]]></description><link>https://springuniverse.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Fri, 20 Nov 2026 19:45:48 GMT</lastBuildDate><atom:link href="https://springuniverse.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[OAuth with SPAs and a Shared BFF]]></title><description><![CDATA[GitHub: github.com/mnafshin/oauth A backend-for-frontend (BFF) that handles OAuth for two single-page apps: React (Vite, port 5173) Angular (port 4200)…]]></description><link>https://springuniverse.hashnode.dev/oauth-with-spas-and-a-shared-bff</link><guid isPermaLink="true">https://springuniverse.hashnode.dev/oauth-with-spas-and-a-shared-bff</guid><dc:creator><![CDATA[Afshin Amini]]></dc:creator><pubDate>Sun, 05 Jul 2026 20:01:39 GMT</pubDate><content:encoded><![CDATA[<p><strong>GitHub:</strong> <a href="https://github.com/mnafshin/oauth">github.com/mnafshin/oauth</a></p>
<hr />
<h2>What we are building</h2>
<p>A <strong>backend-for-frontend (BFF)</strong> that handles OAuth for two single-page apps:</p>
<ol>
<li><p><strong>React</strong> (Vite, port 5173)</p>
</li>
<li><p><strong>Angular</strong> (port 4200)</p>
</li>
</ol>
<p>Both SPAs share one Spring Boot BFF on port <strong>8083</strong>. The BFF:</p>
<ul>
<li><p>Holds the <code>client_secret</code> and exchanges authorization codes</p>
</li>
<li><p>Stores tokens server-side and issues a <strong>session cookie</strong></p>
</li>
<li><p>Exposes a small REST API the SPAs call with <code>credentials: 'include'</code></p>
</li>
<li><p>Redirects back to whichever SPA started login (<code>returnTo</code> URL)</p>
</li>
</ul>
<p>The SPAs never see access tokens, refresh tokens, or <code>client_secret</code>. That is the point.</p>
<p><strong>Repo:</strong> <a href="https://github.com/mnafshin/oauth">oauth-demo</a> → <code>modules/frontend/</code> (<code>bff/</code>, <code>react/</code>, <code>angular/</code>)</p>
<blockquote>
<p><strong>Server-rendered HTML?</strong> See <a href="./06-spring-security-oauth-client.md">post 6</a> — Thymeleaf on port 8080 uses the same Spring OAuth skills but no CORS or cross-origin cookies.</p>
</blockquote>
<hr />
<h2>Why not OAuth inside the browser?</h2>
<p>Post 3 explained Authorization Code + PKCE for public clients. That works, but for typical product SPAs teams prefer a BFF because:</p>
<table>
<thead>
<tr>
<th>Concern</th>
<th>Browser-only SPA</th>
<th>BFF</th>
</tr>
</thead>
<tbody><tr>
<td><code>client_secret</code></td>
<td>Cannot store safely</td>
<td>Stays on server</td>
</tr>
<tr>
<td>Refresh token</td>
<td>Risky in JS storage</td>
<td>Server-side only</td>
</tr>
<tr>
<td>Token exposure</td>
<td>XSS can steal tokens</td>
<td>HttpOnly session cookie</td>
</tr>
<tr>
<td>API calls</td>
<td>Bearer token in JS</td>
<td>Cookie + optional CSRF</td>
</tr>
</tbody></table>
<p>The BFF pattern trades a small backend for a simpler security story in the browser.</p>
<hr />
<h2>Architecture</h2>
<img src="https://cdn.hashnode.com/uploads/covers/69722030e94f080c107ed87f/f036bb70-07e3-4547-9370-8965a2d8b289.png" alt="" style="display:block;margin:0 auto" />

<hr />
<h2>Repo layout</h2>
<pre><code class="language-text">modules/frontend/
├── bff/       # Gradle module :spa-bff — Spring Boot OAuth + REST
├── react/     # Vite + React + TypeScript
└── angular/   # Angular standalone components
</code></pre>
<p>Gradle registers the BFF as <code>:spa-bff</code> in <code>settings.gradle</code>. The Thymeleaf demo (<code>modules/spring-boot</code>) is intentionally separate — compare both patterns side by side.</p>
<hr />
<h2>Run locally</h2>
<pre><code class="language-bash"># Terminal 1 — IdP (imports spa-bff client + app-user role for alice)
make start-keycloak

# Terminal 2 — shared BFF
export KEYCLOAK_SPA_BFF_SECRET=spa-bff-secret
make start-bff

# Terminal 3 — pick one SPA
make start-react      # http://localhost:5173
# or
make start-angular    # http://localhost:4200
</code></pre>
<ol>
<li><p>Open the SPA home page</p>
</li>
<li><p>Click <strong>Login with Keycloak</strong></p>
</li>
<li><p>Sign in as <code>alice</code> / <code>password</code></p>
</li>
<li><p>Land on <code>/dashboard</code> with username and email</p>
</li>
</ol>
<p><code>/api/dashboard</code> requires the <code>spa-bff</code> client role <code>app-user</code> — same role name as the Thymeleaf demo, but on a different Keycloak client.</p>
<h3>Build everything</h3>
<pre><code class="language-bash">make clean-build   # Gradle test + build + both SPA production bundles
</code></pre>
<p>Each module has its own <code>Makefile</code> with <code>start</code>, <code>build</code>, and <code>clean</code> targets.</p>
<hr />
<h2>BFF configuration</h2>
<p><code>modules/frontend/bff/src/main/resources/application.properties</code>:</p>
<pre><code class="language-properties">spring.application.name=oauth-bff
server.port=8083

spring.security.oauth2.client.registration.keycloak.client-id=spa-bff
spring.security.oauth2.client.registration.keycloak.client-secret=${KEYCLOAK_SPA_BFF_SECRET:spa-bff-secret}
spring.security.oauth2.client.registration.keycloak.scope=openid,profile,email
spring.security.oauth2.client.registration.keycloak.authorization-grant-type=authorization_code
spring.security.oauth2.client.registration.keycloak.redirect-uri={baseUrl}/login/oauth2/code/{registrationId}

spring.security.oauth2.client.provider.keycloak.issuer-uri=http://localhost:8081/realms/oauth-demo

app.cors-allowed-origins[0]=http://localhost:5173
app.cors-allowed-origins[1]=http://localhost:4200
app.allowed-return-urls[0]=http://localhost:5173
app.allowed-return-urls[1]=http://localhost:4200
</code></pre>
<ul>
<li><p><code>app.cors-allowed-origins</code> — browsers on 5173/4200 may call the BFF with cookies</p>
</li>
<li><p><code>app.allowed-return-urls</code> — whitelist for post-login redirect (open redirect protection)</p>
</li>
</ul>
<hr />
<h2>BFF security highlights</h2>
<p>Compared to the Thymeleaf app (post 6), the BFF adds three SPA-specific concerns:</p>
<h3>1. CORS with credentials</h3>
<pre><code class="language-java">config.setAllowedOrigins(appProperties.corsAllowedOrigins());
config.setAllowCredentials(true);
</code></pre>
<p>Without <code>AllowCredentials</code>, the browser will not send the session cookie on cross-origin <code>fetch</code> calls.</p>
<h3>2. CSRF for state-changing requests</h3>
<pre><code class="language-java">.csrf(csrf -&gt; csrf
    .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
)
</code></pre>
<p>SPAs read the <code>XSRF-TOKEN</code> cookie and send <code>X-XSRF-TOKEN</code> on <code>POST /logout</code>. Thymeleaf embeds CSRF in forms instead.</p>
<h3>3. API returns 401, not a login redirect</h3>
<pre><code class="language-java">.exceptionHandling(ex -&gt; ex
    .authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED))
)
</code></pre>
<p>SPAs handle 401 in JavaScript (show a login button). Server-rendered apps redirect to <code>/oauth2/authorization/keycloak</code> automatically.</p>
<h3>4. Custom login entry with <code>returnTo</code></h3>
<pre><code class="language-java">@GetMapping("/api/auth/login")
public void login(@RequestParam("returnTo") String returnTo, ...) {
    if (!isAllowedReturnUrl(returnTo)) {
        throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "returnTo is not allowed");
    }
    session.setAttribute("OAUTH_RETURN_TO", returnTo);
    response.sendRedirect("/oauth2/authorization/keycloak");
}
</code></pre>
<p>After OAuth succeeds, a custom <code>AuthenticationSuccessHandler</code> reads <code>OAUTH_RETURN_TO</code> from the session and redirects the browser back to React or Angular.</p>
<h3>5. Role mapping from <code>spa-bff</code> claims</h3>
<p>Same pattern as post 6, but the client ID in <code>resource_access</code> is <code>spa-bff</code>:</p>
<pre><code class="language-java">Map&lt;String, Object&gt; clientAccess =
        (Map&lt;String, Object&gt;) resourceAccess.get("spa-bff");
</code></pre>
<hr />
<h2>REST API</h2>
<table>
<thead>
<tr>
<th>Endpoint</th>
<th>Auth</th>
<th>Purpose</th>
</tr>
</thead>
<tbody><tr>
<td><code>GET /api/auth/login?returnTo=...</code></td>
<td>Public</td>
<td>Start OAuth, remember SPA URL</td>
</tr>
<tr>
<td><code>GET /api/me</code></td>
<td>Session</td>
<td>Current user JSON</td>
</tr>
<tr>
<td><code>GET /api/dashboard</code></td>
<td>Session + <code>ROLE_app-user</code></td>
<td>Protected demo data</td>
</tr>
<tr>
<td><code>POST /logout</code></td>
<td>Session + CSRF</td>
<td>App logout + OIDC logout</td>
</tr>
</tbody></table>
<hr />
<h2>React client</h2>
<p><code>modules/frontend/react/src/api/bff.ts</code> — thin wrapper around <code>fetch</code>:</p>
<pre><code class="language-typescript">export const BFF_URL = import.meta.env.VITE_BFF_URL ?? 'http://localhost:8083'

export function login(returnTo: string): void {
  const url = new URL(`${BFF_URL}/api/auth/login`)
  url.searchParams.set('returnTo', returnTo)
  window.location.href = url.toString()
}

export async function fetchDashboard(): Promise&lt;SessionUser&gt; {
  const response = await fetch(`${BFF_URL}/api/dashboard`, {
    credentials: 'include',
  })
  if (!response.ok) throw new Error(`Dashboard request failed: ${response.status}`)
  return response.json()
}

export async function logout(): Promise&lt;void&gt; {
  const csrfToken = document.cookie.match(/(?:^|;\s*)XSRF-TOKEN=([^;]+)/)?.[1]
  await fetch(`${BFF_URL}/logout`, {
    method: 'POST',
    credentials: 'include',
    headers: csrfToken ? { 'X-XSRF-TOKEN': decodeURIComponent(csrfToken) } : {},
  })
  window.location.href = '/'
}
</code></pre>
<p>The dashboard page calls <code>fetchDashboard()</code> on mount. If the user is not logged in, the BFF returns <strong>401</strong> and the UI shows a login button.</p>
<hr />
<h2>Angular client</h2>
<p><code>modules/frontend/angular/src/app/auth.service.ts</code> — same contract, Angular idioms:</p>
<pre><code class="language-typescript">const BFF_URL = 'http://localhost:8083';

login(returnTo: string): void {
  const url = new URL(`${BFF_URL}/api/auth/login`);
  url.searchParams.set('returnTo', returnTo);
  window.location.href = url.toString();
}

fetchDashboard(): Observable&lt;SessionUser&gt; {
  return this.http.get&lt;SessionUser&gt;(`${BFF_URL}/api/dashboard`, {
    withCredentials: true,
  });
}
</code></pre>
<p><code>provideHttpClient(withFetch())</code> in <code>app.config.ts</code> enables the Fetch API backend. Components inject <code>AuthService</code> — no OAuth library required because the BFF owns the protocol.</p>
<hr />
<h2>Cross-origin cookies in local dev</h2>
<p>React runs on <code>localhost:5173</code>, the BFF on <code>localhost:8083</code>. These are <strong>different origins</strong> (port matters). The session cookie is set for <code>:8083</code> during the OAuth callback; the SPA sends it back on API calls because:</p>
<ol>
<li><p><code>fetch</code> / <code>HttpClient</code> uses <code>credentials: 'include'</code> / <code>withCredentials: true</code></p>
</li>
<li><p>CORS allows credentials from the SPA origin</p>
</li>
<li><p>The cookie is <strong>not</strong> <code>SameSite=Strict</code> blocking cross-site subrequests in this dev setup</p>
</li>
</ol>
<p>In production, teams often serve the SPA and BFF under one parent domain (e.g. <code>app.example.com</code> and <code>app.example.com/api</code>) to simplify cookies — or use a reverse proxy on a single origin.</p>
<hr />
<h2>Thymeleaf vs BFF vs plain Java</h2>
<table>
<thead>
<tr>
<th></th>
<th>Thymeleaf (post 6)</th>
<th>BFF (this post)</th>
<th>Plain Java (post 7)</th>
</tr>
</thead>
<tbody><tr>
<td>Port</td>
<td>8080</td>
<td>8083</td>
<td>8082</td>
</tr>
<tr>
<td>Keycloak client</td>
<td><code>orders-web</code></td>
<td><code>spa-bff</code></td>
<td><code>orders-web</code></td>
</tr>
<tr>
<td>UI</td>
<td>Server HTML</td>
<td>React / Angular</td>
<td>Hand-rolled HTML</td>
</tr>
<tr>
<td>OAuth code</td>
<td>Spring Security</td>
<td>Spring Security</td>
<td>Manual HttpClient</td>
</tr>
<tr>
<td>CORS</td>
<td>Not needed</td>
<td>Required</td>
<td>Not needed</td>
</tr>
<tr>
<td>CSRF</td>
<td>Form hidden field</td>
<td>Cookie + header</td>
<td>You implement</td>
</tr>
</tbody></table>
<p>All three enforce <code>app-user</code> — the authorization rule is the same; only the integration shape changes.</p>
<hr />
<h2>Go deeper</h2>
<h3>Serving the SPA from the BFF (single origin)</h3>
<p>For production, build the React/Angular app and copy static files into <code>src/main/resources/static</code> on the BFF. One port, no CORS, simpler cookies. The OAuth redirect URI stays on the BFF host.</p>
<h3>Token relay to downstream APIs</h3>
<p>The BFF can call microservices with the user's access token server-side:</p>
<pre><code class="language-java">@RegisteredOAuth2AuthorizedClient("keycloak") OAuth2AuthorizedClient client
</code></pre>
<p>The SPA never sees the Bearer token.</p>
<h3>Adding a third SPA</h3>
<p>Add its dev-server origin to <code>app.cors-allowed-origins</code> and <code>app.allowed-return-urls</code>. No new Keycloak client required — that is why the BFF is shared.</p>
<h3>Testing the BFF</h3>
<p><code>ApiControllerTest</code> uses MockMvc + <code>oauth2Login()</code> — same approach as post 6. End-to-end tests need Keycloak (docker-compose) or Testcontainers.</p>
<hr />
<h2>What you should know after this post</h2>
<ul>
<li><p>[ ] You understand why SPAs use a BFF instead of storing tokens in the browser</p>
</li>
<li><p>[ ] You can run the shared BFF with React or Angular against local Keycloak</p>
</li>
<li><p>[ ] You know the extra Spring Security pieces: CORS, CSRF cookie, 401 entry point, <code>returnTo</code> whitelist</p>
</li>
<li><p>[ ] You can explain when to use Thymeleaf OAuth (post 6) vs a BFF (this post)</p>
</li>
<li><p>[ ] You have seen the same authorization rule (<code>app-user</code>) across all demo apps</p>
</li>
</ul>
<hr />
]]></content:encoded></item><item><title><![CDATA[Keycloak Integration End to End]]></title><description><![CDATA[GitHub: github.com/mnafshin/oauth Stand up Keycloak locally, create realm clients, and connect the demos from posts 6–9: Thymeleaf Spring Boot (orders-web…]]></description><link>https://springuniverse.hashnode.dev/keycloak-integration-end-to-end</link><guid isPermaLink="true">https://springuniverse.hashnode.dev/keycloak-integration-end-to-end</guid><dc:creator><![CDATA[Afshin Amini]]></dc:creator><pubDate>Sun, 05 Jul 2026 19:56:01 GMT</pubDate><content:encoded><![CDATA[<p><strong>GitHub:</strong> <a href="https://github.com/mnafshin/oauth">github.com/mnafshin/oauth</a></p>
<hr />
<h2>Goal</h2>
<p>Stand up Keycloak locally, create realm clients, and connect the demos from posts 6–9:</p>
<ul>
<li><p><strong>Thymeleaf Spring Boot</strong> (<code>orders-web</code> on port 8080)</p>
</li>
<li><p><strong>Plain Java</strong> (<code>orders-web</code> on port 8082)</p>
</li>
<li><p><strong>Shared SPA BFF</strong> (<code>spa-bff</code> on port 8083) for React and Angular</p>
</li>
</ul>
<p>Okta and Auth0 follow the same OIDC steps with different admin UIs — application configuration changes only <code>issuer-uri</code>, <code>client-id</code>, and secrets.</p>
<hr />
<h2>Quick start (demo repo)</h2>
<p>If you cloned <a href="https://github.com/mnafshin/oauth">oauth-demo</a>, skip manual realm setup — import runs on first start:</p>
<pre><code class="language-bash">make start-keycloak
# or:
cd modules/keycloak &amp;&amp; docker compose up -d
</code></pre>
<p>This starts Keycloak <strong>26.6.3</strong> on port <strong>8081</strong> and imports <code>realms/oauth-demo-realm.json</code>:</p>
<table>
<thead>
<tr>
<th>Resource</th>
<th>Value</th>
</tr>
</thead>
<tbody><tr>
<td>Admin console</td>
<td><a href="http://localhost:8081/admin">http://localhost:8081/admin</a> (<code>admin</code> / <code>admin</code>)</td>
</tr>
<tr>
<td>Realm</td>
<td><code>oauth-demo</code></td>
</tr>
<tr>
<td>Client <code>orders-web</code></td>
<td>confidential — Thymeleaf + plain Java</td>
</tr>
<tr>
<td>Client <code>spa-bff</code></td>
<td>confidential — shared BFF for React + Angular</td>
</tr>
<tr>
<td>Client secret <code>orders-web</code></td>
<td><code>orders-web-secret</code> (local demo only)</td>
</tr>
<tr>
<td>Client secret <code>spa-bff</code></td>
<td><code>spa-bff-secret</code> (local demo only)</td>
</tr>
<tr>
<td>Test user</td>
<td><code>alice</code> / <code>password</code></td>
</tr>
<tr>
<td>Client role</td>
<td><code>app-user</code> on both clients (assigned to <code>alice</code>)</td>
</tr>
</tbody></table>
<h3>Redirect URIs (must match exactly)</h3>
<table>
<thead>
<tr>
<th>App</th>
<th>Redirect URI</th>
</tr>
</thead>
<tbody><tr>
<td>Thymeleaf Spring Boot (:8080)</td>
<td><code>http://localhost:8080/login/oauth2/code/keycloak</code></td>
</tr>
<tr>
<td>Plain Java (:8082)</td>
<td><code>http://localhost:8082/callback</code></td>
</tr>
<tr>
<td>SPA BFF (:8083)</td>
<td><code>http://localhost:8083/login/oauth2/code/keycloak</code></td>
</tr>
</tbody></table>
<h3>Run the Thymeleaf demo</h3>
<pre><code class="language-bash">export KEYCLOAK_CLIENT_SECRET=orders-web-secret
make start-spring-boot
</code></pre>
<p>Visit <code>http://localhost:8080/dashboard</code> and log in as <code>alice</code>.</p>
<h3>Run the SPA stack</h3>
<pre><code class="language-bash">export KEYCLOAK_SPA_BFF_SECRET=spa-bff-secret
make start-bff        # terminal 1
make start-react      # or: make start-angular
</code></pre>
<p>Open <a href="http://localhost:5173">http://localhost:5173</a> or <a href="http://localhost:4200">http://localhost:4200</a> — details in SPA post.</p>
<p><code>start-dev</code> is for local development only — not production topology.</p>
<hr />
<h2>Manual setup (understand what the import contains)</h2>
<p>Use this path if you are not using the repo import, or you want to learn the admin console steps behind the JSON file.</p>
<h3>Start Keycloak with Docker</h3>
<pre><code class="language-bash">docker run --name keycloak -p 8081:8080 \
  -e KC_BOOTSTRAP_ADMIN_USERNAME=admin \
  -e KC_BOOTSTRAP_ADMIN_PASSWORD=admin \
  quay.io/keycloak/keycloak:26.6.3 start-dev
</code></pre>
<table>
<thead>
<tr>
<th>URL</th>
<th>Purpose</th>
</tr>
</thead>
<tbody><tr>
<td><code>http://localhost:8081/admin</code></td>
<td>Admin console</td>
</tr>
<tr>
<td><code>http://localhost:8081/realms/oauth-demo/...</code></td>
<td>Realm endpoints (after creation)</td>
</tr>
</tbody></table>
<hr />
<h2>Create realm</h2>
<ol>
<li><p>Admin console → <strong>Create realm</strong></p>
</li>
<li><p>Name: <code>oauth-demo</code></p>
</li>
<li><p>Enabled: ON</p>
</li>
</ol>
<p>Realms isolate users, clients, and keys. Use separate realms per environment (or separate Keycloak instances).</p>
<hr />
<h2>Create client for Spring Boot (<code>orders-web</code>)</h2>
<p><strong>Clients → Create client</strong></p>
<table>
<thead>
<tr>
<th>Setting</th>
<th>Value</th>
</tr>
</thead>
<tbody><tr>
<td>Client ID</td>
<td><code>orders-web</code></td>
</tr>
<tr>
<td>Client type</td>
<td>OpenID Connect</td>
</tr>
<tr>
<td>Client authentication</td>
<td><strong>ON</strong> (confidential — has secret)</td>
</tr>
</tbody></table>
<p><strong>Capability config:</strong></p>
<ul>
<li><p>Client authentication: ON</p>
</li>
<li><p>Authorization: OFF (we use simple OIDC login first)</p>
</li>
<li><p>Standard flow: <strong>ON</strong> (Authorization Code)</p>
</li>
<li><p>Direct access grants: OFF (no password grant)</p>
</li>
</ul>
<p><strong>Login settings:</strong></p>
<table>
<thead>
<tr>
<th>Field</th>
<th>Value</th>
</tr>
</thead>
<tbody><tr>
<td>Root URL</td>
<td><code>http://localhost:8080</code></td>
</tr>
<tr>
<td>Valid redirect URIs</td>
<td><code>http://localhost:8080/login/oauth2/code/keycloak</code>, <code>http://localhost:8082/callback</code></td>
</tr>
<tr>
<td>Valid post logout redirect URIs</td>
<td><code>http://localhost:8080/</code></td>
</tr>
<tr>
<td>Web origins</td>
<td><code>http://localhost:8080</code></td>
</tr>
</tbody></table>
<p>Save → <strong>Credentials</strong> tab → copy <strong>Client secret</strong> → <code>export KEYCLOAK_CLIENT_SECRET=...</code></p>
<p><strong>Clients → orders-web → Roles → Create</strong> <code>app-user</code> (application role for the Thymeleaf dashboard).</p>
<hr />
<h2>Create client for the SPA BFF (<code>spa-bff</code>)</h2>
<p>Repeat the same steps with a <strong>second client</strong> for the shared BFF (post 9):</p>
<table>
<thead>
<tr>
<th>Setting</th>
<th>Value</th>
</tr>
</thead>
<tbody><tr>
<td>Client ID</td>
<td><code>spa-bff</code></td>
</tr>
<tr>
<td>Client authentication</td>
<td>ON (confidential)</td>
</tr>
<tr>
<td>Standard flow</td>
<td>ON</td>
</tr>
<tr>
<td>Root URL</td>
<td><code>http://localhost:8083</code></td>
</tr>
<tr>
<td>Valid redirect URIs</td>
<td><code>http://localhost:8083/login/oauth2/code/keycloak</code></td>
</tr>
<tr>
<td>Valid post logout redirect URIs</td>
<td><code>http://localhost:5173/*</code>, <code>http://localhost:4200/*</code></td>
</tr>
<tr>
<td>Web origins</td>
<td><code>http://localhost:8083</code>, <code>http://localhost:5173</code>, <code>http://localhost:4200</code></td>
</tr>
</tbody></table>
<p><strong>Credentials</strong> → copy secret → <code>export KEYCLOAK_SPA_BFF_SECRET=...</code></p>
<p><strong>Roles → Create</strong> <code>app-user</code> on <code>spa-bff</code>. Assign it to <code>alice</code> under <strong>Users → Role mapping → Client roles</strong>.</p>
<p>Why a separate client? The BFF runs on a different port, uses REST instead of Thymeleaf, and serves multiple SPA origins. Keeping clients separate mirrors how teams split server-rendered apps from API gateways in production.</p>
<hr />
<h2>Create a test user</h2>
<p><strong>Users → Create user</strong></p>
<ul>
<li><p>Username: <code>alice</code></p>
</li>
<li><p>Email verified: ON<br /><strong>Credentials</strong> tab → set password (e.g. <code>password</code>) → Temporary: OFF<br /><strong>Role mapping → Client roles</strong> → select <code>orders-web</code> → assign <code>app-user</code></p>
</li>
</ul>
<p>Without <code>app-user</code>, <code>alice</code> can log in but the app returns <strong>403</strong> on protected routes (<code>@PreAuthorize("hasRole('app-user')")</code> in posts 6 and 9).</p>
<h2>Verify OIDC discovery</h2>
<pre><code class="language-bash">curl -s http://localhost:8081/realms/oauth-demo/.well-known/openid-configuration | jq .
</code></pre>
<p>Confirm:</p>
<ul>
<li><p><code>authorization_endpoint</code></p>
</li>
<li><p><code>token_endpoint</code></p>
</li>
<li><p><code>jwks_uri</code></p>
</li>
<li><p><code>issuer</code> = <code>http://localhost:8081/realms/oauth-demo</code></p>
</li>
</ul>
<p>Spring <code>issuer-uri</code> must match <code>issuer</code> exactly (including host and port).</p>
<hr />
<h2>Spring configuration (recap)</h2>
<p><strong>Thymeleaf app</strong> (<code>modules/spring-boot</code>):</p>
<pre><code class="language-properties">spring.security.oauth2.client.registration.keycloak.client-id=orders-web
spring.security.oauth2.client.registration.keycloak.client-secret=${KEYCLOAK_CLIENT_SECRET:orders-web-secret}
spring.security.oauth2.client.registration.keycloak.scope=openid,profile,email
spring.security.oauth2.client.provider.keycloak.issuer-uri=http://localhost:8081/realms/oauth-demo
</code></pre>
<p><strong>SPA BFF</strong> (<code>modules/frontend/bff</code>):</p>
<pre><code class="language-properties">spring.security.oauth2.client.registration.keycloak.client-id=spa-bff
spring.security.oauth2.client.registration.keycloak.client-secret=${KEYCLOAK_SPA_BFF_SECRET:spa-bff-secret}
spring.security.oauth2.client.provider.keycloak.issuer-uri=http://localhost:8081/realms/oauth-demo
app.cors-allowed-origins[0]=http://localhost:5173
app.cors-allowed-origins[1]=http://localhost:4200
app.allowed-return-urls[0]=http://localhost:5173
app.allowed-return-urls[1]=http://localhost:4200
</code></pre>
<p>Run from the repo root:</p>
<pre><code class="language-bash">export KEYCLOAK_CLIENT_SECRET=orders-web-secret
make start-spring-boot

export KEYCLOAK_SPA_BFF_SECRET=spa-bff-secret
make start-bff
</code></pre>
<hr />
<h2>Custom scopes and API audience</h2>
<p>When your API validates access tokens:</p>
<h3>1. Create client scope (optional)</h3>
<p><strong>Client scopes → Create</strong></p>
<ul>
<li><p>Name: <code>orders:read</code></p>
</li>
<li><p>Include in token scope: ON</p>
</li>
</ul>
<p>Assign to <code>orders-web</code> under <strong>Client scopes</strong> tab.</p>
<h3>2. Create resource server client (API)</h3>
<p>Some teams use a separate <strong>audience</strong> client or Keycloak <strong>authorization services</strong>. Minimal approach:</p>
<ul>
<li><p>API validates JWTs minted by the same realm</p>
</li>
<li><p>Check <code>scope</code> claim contains <code>orders:read</code></p>
</li>
<li><p>Or map client roles to service permissions</p>
</li>
</ul>
<h3>3. Spring resource server (snippet)</h3>
<p>For a stateless API module:</p>
<pre><code class="language-gradle">implementation 'org.springframework.boot:spring-boot-starter-oauth2-resource-server'
</code></pre>
<pre><code class="language-properties">spring.security.oauth2.resourceserver.jwt.issuer-uri=http://localhost:8081/realms/oauth-demo
</code></pre>
<pre><code class="language-java">http.authorizeHttpRequests(auth -&gt; auth
    .requestMatchers(HttpMethod.GET, "/api/orders/**").hasAuthority("SCOPE_orders:read")
    .anyRequest().authenticated()
).oauth2ResourceServer(oauth2 -&gt; oauth2.jwt(Customizer.withDefaults()));
</code></pre>
<hr />
<h2>Client roles in tokens</h2>
<p>The manual steps above create <code>app-user</code> on <code>orders-web</code> and assign it to <code>alice</code>. The imported realm JSON does the same under <code>roles.client</code> and <code>users[].clientRoles</code>.</p>
<p>Assigned client roles show up under <code>resource_access.&lt;client-id&gt;.roles</code> in the <strong>access token</strong> by default. Keycloak does not always copy them into the ID token unless you enable <strong>Add to ID token</strong> on the client-roles protocol mapper (the imported realm JSON does this for both <code>orders-web</code> and <code>spa-bff</code>). The plain Java demo checks the access token; Spring maps from the ID token — enable the mapper if protected routes return 403 after login.</p>
<hr />
<h2>Logout (complete the story)</h2>
<p>The demo repo configures RP-initiated OIDC logout in <code>SecurityConfig</code>:</p>
<pre><code class="language-java">@Bean
LogoutSuccessHandler oidcLogoutSuccessHandler(
        ClientRegistrationRepository clientRegistrationRepository) {
    OidcClientInitiatedLogoutSuccessHandler handler =
            new OidcClientInitiatedLogoutSuccessHandler(clientRegistrationRepository);
    handler.setPostLogoutRedirectUri("{baseUrl}/");
    return handler;
}
</code></pre>
<p>Wire it on the filter chain with <code>.logout(logout -&gt; logout.logoutSuccessHandler(oidcLogoutSuccessHandler))</code>.</p>
<p>Keycloak must allow the post-logout redirect URI on the <code>orders-web</code> client (<code>http://localhost:8080/</code>). The imported realm JSON sets this via the client attribute <code>post.logout.redirect.uris</code>.</p>
<p>Under the hood, Spring redirects the browser to:</p>
<pre><code class="language-text">http://localhost:8081/realms/oauth-demo/protocol/openid-connect/logout
  ?client_id=orders-web
  &amp;post_logout_redirect_uri=http://localhost:8080/
  &amp;id_token_hint=...
</code></pre>
<p>Without this, Alice logs out of your app but her Keycloak SSO session remains.</p>
<hr />
<h2>Export realm for reproducibility</h2>
<p>The demo repo already ships <code>modules/keycloak/realms/oauth-demo-realm.json</code>. To regenerate after UI changes:</p>
<p><strong>Realm settings → Action → Partial export</strong> (or use <a href="https://registry.terraform.io/providers/keycloak/keycloak/latest/docs">Keycloak Terraform provider</a> for teams).</p>
<p>Check into git under <code>modules/keycloak/realms/</code> — exclude production secrets; inject via env or CI. The imported demo file includes a fixed local secret for convenience; treat that as dev-only.</p>
<hr />
<h2>Keycloak vs Okta (same integration, different ops)</h2>
<table>
<thead>
<tr>
<th>Task</th>
<th>Keycloak</th>
<th>Okta</th>
</tr>
</thead>
<tbody><tr>
<td>Create app</td>
<td>Clients → Create</td>
<td>Applications → App integrations</td>
</tr>
<tr>
<td>Issuer</td>
<td><code>/realms/{realm}</code></td>
<td><code>https://{org}.okta.com/oauth2/default</code></td>
</tr>
<tr>
<td>Get secret</td>
<td>Credentials tab</td>
<td>Client secret in app settings</td>
</tr>
<tr>
<td>Local dev</td>
<td>Docker on laptop</td>
<td>Okta developer org (cloud)</td>
</tr>
</tbody></table>
<p>Spring <code>application.properties</code> structure is identical; only URLs and IDs change.</p>
<hr />
<h2>What Keycloak still does not do</h2>
<p>Even with a working realm:</p>
<ul>
<li><p>Your business authorization rules</p>
</li>
<li><p>Session storage scaling (Redis, JDBC)</p>
</li>
<li><p>Production HA, backups, upgrades</p>
</li>
<li><p>User onboarding emails and product UX</p>
</li>
</ul>
<p>Re-read the identity providers post before go-live.</p>
<hr />
<h2>Go deeper</h2>
<h3>Identity brokering</h3>
<p>Keycloak can front Google or Azure AD — users still see Keycloak realm URLs; brokers handle federation.</p>
<h3>Organizations and multi-tenancy</h3>
<p>Multiple realms vs single realm with attributes — choose based on isolation requirements.</p>
<h3>Harderning for production</h3>
<ul>
<li><p><code>start</code> with optimized profile, PostgreSQL backend</p>
</li>
<li><p>Reverse proxy TLS termination</p>
</li>
<li><p>Disable admin console on public internet</p>
</li>
<li><p>Brute force detection enabled (Realm settings → Security defenses)</p>
</li>
</ul>
<hr />
<h2>What you should know after this post</h2>
<ul>
<li><p>[ ] You can run Keycloak locally and create confidential OIDC clients with client roles</p>
</li>
<li><p>[ ] Thymeleaf and BFF apps log in via discovered OIDC endpoints</p>
</li>
<li><p>[ ] You know how to assign client roles (e.g. <code>app-user</code>) and map them in Spring</p>
</li>
<li><p>[ ] You know how to add scopes and resource server JWT validation</p>
</li>
<li><p>[ ] You have a path to export realm config and plan production hardening</p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[OAuth in Plain Java]]></title><description><![CDATA[GitHub: github.com/mnafshin/oauth Spring Security hides PKCE, state, discovery, and token exchange behind auto-configuration. That is good for productivity…]]></description><link>https://springuniverse.hashnode.dev/oauth-in-plain-java</link><guid isPermaLink="true">https://springuniverse.hashnode.dev/oauth-in-plain-java</guid><dc:creator><![CDATA[Afshin Amini]]></dc:creator><pubDate>Sun, 05 Jul 2026 19:50:25 GMT</pubDate><content:encoded><![CDATA[<p><strong>GitHub:</strong> <a href="https://github.com/mnafshin/oauth">github.com/mnafshin/oauth</a></p>
<hr />
<h2>Why this post exists</h2>
<p>Spring Security hides PKCE, <code>state</code>, discovery, and token exchange behind auto-configuration. That is good for productivity — bad for interviews and incident debugging.</p>
<p>Here we implement <strong>Authorization Code + PKCE</strong> with Java's built-in <code>HttpClient</code> and a minimal embedded HTTP server (or servlet). No Spring Security.</p>
<p>After this post, Spring's magic becomes <strong>named steps</strong> you already understand from the Authorization Code + PKCE walkthrough.</p>
<hr />
<h2>Demo repo</h2>
<p>The <a href="https://github.com/mnafshin/oauth">oauth-demo</a> monorepo ships a runnable module at <code>modules/plain-java</code>:</p>
<pre><code class="language-bash">make start-keycloak
make start-plain-java
# or:
# docker compose -f modules/keycloak/docker-compose.yml up -d
# ./gradlew :plain-java:run
</code></pre>
<table>
<thead>
<tr>
<th>Setting</th>
<th>Value</th>
</tr>
</thead>
<tbody><tr>
<td>App URL</td>
<td><a href="http://localhost:8082">http://localhost:8082</a></td>
</tr>
<tr>
<td>Redirect URI</td>
<td><code>http://localhost:8082/callback</code></td>
</tr>
<tr>
<td>Client</td>
<td><code>orders-web</code> / <code>orders-web-secret</code> (same Keycloak realm as the Thymeleaf Spring Boot post)</td>
</tr>
<tr>
<td>Test user</td>
<td><code>alice</code> / <code>password</code></td>
</tr>
</tbody></table>
<p>Visit <code>/dashboard</code> — the app requires the <code>app-user</code> client role on <code>orders-web</code>, same as the Thymeleaf demo on port 8080. The SPA BFF demo (post 9) uses a separate Keycloak client <code>spa-bff</code> on port 8083.</p>
<hr />
<h2>Architecture</h2>
<img src="https://cdn.hashnode.com/uploads/covers/69722030e94f080c107ed87f/7e4c438c-375e-4205-b5b0-dddf93dfbb1e.png" alt="" style="display:block;margin:0 auto" />

<p>We store:</p>
<ul>
<li><p><code>state</code> + <code>code_verifier</code> in server-side session (in-memory <code>ConcurrentHashMap</code> for demo)</p>
</li>
<li><p>Session ID in httpOnly cookie</p>
</li>
</ul>
<hr />
<h2>Step 1 — PKCE and state utilities</h2>
<pre><code class="language-java">import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Base64;

public final class Pkce {

    private static final SecureRandom RANDOM = new SecureRandom();

    public static String randomUrlSafe(int bytes) {
        byte[] buf = new byte[bytes];
        RANDOM.nextBytes(buf);
        return Base64.getUrlEncoder().withoutPadding().encodeToString(buf);
    }

    public static String codeChallengeS256(String verifier) {
        try {
            byte[] hash = MessageDigest.getInstance("SHA-256")
                .digest(verifier.getBytes(StandardCharsets.US_ASCII));
            return Base64.getUrlEncoder().withoutPadding().encodeToString(hash);
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
    }
}
</code></pre>
<hr />
<h2>Step 2 — Build authorization URL</h2>
<pre><code class="language-java">public URI buildAuthorizeUrl(OidcDiscovery doc, String clientId, String redirectUri,
                             String scope, String state, String codeChallenge) {
    String query = "response_type=code"
        + "&amp;client_id=" + urlEncode(clientId)
        + "&amp;redirect_uri=" + urlEncode(redirectUri)
        + "&amp;scope=" + urlEncode(scope)
        + "&amp;state=" + urlEncode(state)
        + "&amp;code_challenge=" + urlEncode(codeChallenge)
        + "&amp;code_challenge_method=S256";
    return URI.create(doc.authorizationEndpoint() + "?" + query);
}
</code></pre>
<p>Fetch <code>OidcDiscovery</code> once from <code>/.well-known/openid-configuration</code> (parse JSON with Jackson).</p>
<pre><code class="language-java">public record OidcDiscovery(
    String issuer,
    String authorizationEndpoint,
    String tokenEndpoint,
    String jwksUri
) {}
</code></pre>
<h2>Step 3 — Token exchange</h2>
<pre><code class="language-java">public TokenResponse exchangeCode(OidcDiscovery doc, String clientId, String clientSecret,
                                  String redirectUri, String code, String codeVerifier)
        throws IOException, InterruptedException {

    String body = "grant_type=authorization_code"
        + "&amp;code=" + urlEncode(code)
        + "&amp;redirect_uri=" + urlEncode(redirectUri)
        + "&amp;client_id=" + urlEncode(clientId)
        + "&amp;code_verifier=" + urlEncode(codeVerifier);

    HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create(doc.tokenEndpoint()))
        .header("Content-Type", "application/x-www-form-urlencoded")
        .header("Authorization", basicAuth(clientId, clientSecret))
        .POST(HttpRequest.BodyPublishers.ofString(body))
        .build();

    HttpResponse&lt;String&gt; response = HttpClient.newHttpClient()
        .send(request, HttpResponse.BodyHandlers.ofString());

    if (response.statusCode() != 200) {
        throw new IOException("Token error: " + response.body());
    }
    return parseTokenResponse(response.body());
}
</code></pre>
<hr />
<h2>Step 4 — Validate ID token (do not skip)</h2>
<pre><code class="language-java">public JWTClaimsSet validateIdToken(String idTokenJwt, OidcDiscovery doc, String clientId) {
    // Use com.nimbusds:nimbus-jose-jwt
    // 1. Parse JWT and verify RS256 signature against JWKS from doc.jwksUri() (cache keys)
    // 2. require iss == doc.issuer()
    // 3. require aud contains clientId
    // 4. require exp in future (with clock skew)
    return claims;
}
</code></pre>
<p><strong>Do not</strong> parse the payload with <code>Base64.decode</code> and call it a day.</p>
<hr />
<h2>Step 5 — <code>/login</code> handler (conceptual)</h2>
<pre><code class="language-java">void handleLogin(HttpExchange exchange, HttpSession session) throws IOException {
    String state = Pkce.randomUrlSafe(32);
    String verifier = Pkce.randomUrlSafe(64);
    String challenge = Pkce.codeChallengeS256(verifier);

    session.put("oauth_state", state);
    session.put("code_verifier", verifier);

    URI authorize = buildAuthorizeUrl(discovery, CLIENT_ID, REDIRECT_URI,
        "openid profile email", state, challenge);

    exchange.getResponseHeaders().add("Location", authorize.toString());
    exchange.sendResponseHeaders(302, -1);
}
</code></pre>
<hr />
<h2>Step 6 — <code>/callback</code> handler</h2>
<pre><code class="language-java">void handleCallback(HttpExchange exchange, HttpSession session) throws Exception {
    Map&lt;String, String&gt; params = parseQuery(exchange.getRequestURI().getQuery());

    if (!params.get("state").equals(session.get("oauth_state"))) {
        sendError(exchange, 400, "Invalid state");
        return;
    }

    TokenResponse tokens = exchangeCode(discovery, CLIENT_ID, CLIENT_SECRET,
        REDIRECT_URI, params.get("code"), session.get("code_verifier"));

    JwtClaimsSet idToken = validateIdToken(tokens.idToken(), discovery, CLIENT_ID);

    if (!hasAppUserRole(idToken)) {
        sendError(exchange, 403, "Missing app-user role");
        return;
    }

    session.put("user", idToken.getSubject());
    session.put("username", idToken.getStringClaim("preferred_username"));
    session.remove("oauth_state");
    session.remove("code_verifier");
    // Store refresh token server-side only if you need offline access

    redirect(exchange, "/dashboard");
}
</code></pre>
<hr />
<h2>What you feel when it works</h2>
<ol>
<li><p><strong>Redirect URI must match character-for-character</strong> — one trailing slash breaks everything.</p>
</li>
<li><p><strong>Clock skew</strong> — laptop vs Docker VM time drift causes <code>exp</code> validation failures.</p>
</li>
<li><p><strong>Client auth method</strong> — Keycloak may expect POST body secret vs Basic auth; match client config.</p>
</li>
<li><p><strong>Session fixation</strong> — issue new session ID after login.</p>
</li>
</ol>
<hr />
<h2>Comparison: plain Java vs Spring Security</h2>
<table>
<thead>
<tr>
<th>Concern</th>
<th>Plain Java</th>
<th>Spring Security</th>
</tr>
</thead>
<tbody><tr>
<td>PKCE</td>
<td>You generate</td>
<td>Automatic</td>
</tr>
<tr>
<td>State</td>
<td>You store/verify</td>
<td>Automatic</td>
</tr>
<tr>
<td>Discovery</td>
<td>You fetch/cache</td>
<td><code>issuer-uri</code></td>
</tr>
<tr>
<td>Token refresh</td>
<td>You schedule</td>
<td><code>OAuth2AuthorizedClientManager</code></td>
</tr>
<tr>
<td>CSRF on forms</td>
<td>You add</td>
<td>Built-in</td>
</tr>
<tr>
<td>Lines of code</td>
<td>~200–400</td>
<td>~30 config</td>
</tr>
</tbody></table>
<p>Use Spring in production unless you have a compelling reason not to.</p>
<hr />
<h2>Go deeper</h2>
<h3>Refresh token rotation</h3>
<pre><code class="language-java">String body = "grant_type=refresh_token&amp;refresh_token=" + urlEncode(storedRefresh);
// POST to token endpoint; replace stored refresh if server rotates
</code></pre>
<h3>PAR (Pushed Authorization Requests)</h3>
<p>POST authorize parameters to <code>pushed_authorization_request_endpoint</code> first; use returned <code>request_uri</code> in place of long query strings.</p>
<h3>Embedding in non-servlet apps</h3>
<p>Same flow works in Netty, Vert.x, or Lambda@Edge for BFF — HTTP redirects and server-side session storage are universal.</p>
<hr />
<h2>What you should know after this post</h2>
<ul>
<li><p>[ ] You can implement PKCE and state without a framework</p>
</li>
<li><p>[ ] You know ID token validation is mandatory</p>
</li>
<li><p>[ ] You appreciate what Spring Security automates</p>
</li>
<li><p>[ ] You can run the plain Java demo against local Keycloak (<code>make start-plain-java</code>)</p>
</li>
</ul>
<hr />
]]></content:encoded></item><item><title><![CDATA[OAuth with Spring Security]]></title><description><![CDATA[GitHub: github.com/mnafshin/oauth A minimal server-rendered Spring Boot web app that: Redirects unauthenticated users to Keycloak Completes Authorization…]]></description><link>https://springuniverse.hashnode.dev/oauth-with-spring-security</link><guid isPermaLink="true">https://springuniverse.hashnode.dev/oauth-with-spring-security</guid><dc:creator><![CDATA[Afshin Amini]]></dc:creator><pubDate>Sun, 05 Jul 2026 19:47:44 GMT</pubDate><content:encoded><![CDATA[<p><strong>GitHub:</strong> <a href="https://github.com/mnafshin/oauth">github.com/mnafshin/oauth</a></p>
<hr />
<h2>What we are building</h2>
<p>A minimal <strong>server-rendered</strong> Spring Boot web app that:</p>
<ol>
<li><p>Redirects unauthenticated users to Keycloak</p>
</li>
<li><p>Completes Authorization Code + PKCE (Spring handles PKCE automatically)</p>
</li>
<li><p>Establishes a session and shows the logged-in user in Thymeleaf templates</p>
</li>
<li><p>Enforces business authorization on <code>/dashboard</code> via Keycloak client roles and <code>@PreAuthorize</code></p>
</li>
</ol>
<p>This uses the <strong>OAuth 2.0 Login</strong> support in Spring Security — the right default when your UI is rendered on the server (HTML forms, CSRF tokens, same-origin session cookies).</p>
<blockquote>
<p><strong>Building a React or Angular SPA?</strong> That is a different integration pattern — tokens stay on a backend-for-frontend (BFF). This post keeps Thymeleaf deliberately simple so you can compare both approaches in the same repo.</p>
</blockquote>
<p><strong>Repo:</strong> <a href="https://github.com/mnafshin/oauth">oauth-demo</a> → <code>modules/spring-boot</code></p>
<hr />
<h2>Prerequisites</h2>
<ul>
<li><p>Java 21+ (the demo repo targets <strong>Java 25</strong> with <strong>Spring Boot 4.1</strong> — any 21+ JDK works)</p>
</li>
<li><p>Docker (for local Keycloak) — full Keycloak setup is covered in the Keycloak integration post</p>
</li>
<li><p>Keycloak realm with a client configured (we use <code>orders-web</code>) and a client role for app authorization (we use <code>app-user</code>)</p>
</li>
</ul>
<hr />
<h2>Dependencies</h2>
<p>Add to <code>modules/spring-boot/build.gradle</code>:</p>
<pre><code class="language-gradle">plugins {
    id 'java'
    id 'org.springframework.boot' version '4.1.0'
    id 'io.spring.dependency-management' version '1.1.7'
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-security'
    implementation 'org.springframework.boot:spring-boot-starter-oauth2-client'
    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    testImplementation 'org.springframework.boot:spring-boot-starter-webmvc-test'
    testImplementation 'org.springframework.security:spring-security-test'
}
</code></pre>
<ul>
<li><p><code>spring-boot-starter-oauth2-client</code> — OAuth2/OIDC client support, PKCE, JWT parsing for user info</p>
</li>
<li><p><code>spring-boot-starter-thymeleaf</code> — server-rendered views for <code>/</code> and <code>/dashboard</code></p>
</li>
</ul>
<hr />
<h2>Configuration</h2>
<p><code>src/main/resources/application.properties</code>:</p>
<pre><code class="language-properties">spring.application.name=oauth-demo

# Keycloak OIDC (see the Keycloak integration post for realm setup)
spring.security.oauth2.client.registration.keycloak.client-id=orders-web
spring.security.oauth2.client.registration.keycloak.client-secret=${KEYCLOAK_CLIENT_SECRET:orders-web-secret}
spring.security.oauth2.client.registration.keycloak.scope=openid,profile,email
spring.security.oauth2.client.registration.keycloak.authorization-grant-type=authorization_code
spring.security.oauth2.client.registration.keycloak.redirect-uri={baseUrl}/login/oauth2/code/{registrationId}

spring.security.oauth2.client.provider.keycloak.issuer-uri=http://localhost:8081/realms/oauth-demo
</code></pre>
<p><strong>Important:</strong> <code>issuer-uri</code> triggers auto-discovery of authorize, token, and JWKS endpoints from:</p>
<pre><code class="language-text">http://localhost:8081/realms/oauth-demo/.well-known/openid-configuration
</code></pre>
<p>Never hard-code those URLs when Spring can discover them.</p>
<hr />
<h2>Security filter chain</h2>
<p><code>SecurityConfig</code> wires OAuth2 login, OIDC logout, method security, and a mapper that turns Keycloak client roles into Spring authorities. Application roles belong on the client (<code>orders-web</code>), not the realm — Keycloak puts them in <code>resource_access.orders-web.roles</code> on the ID token.</p>
<pre><code class="language-java">package info.mnafshin.oauth_demo;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper;
import org.springframework.security.oauth2.client.oidc.web.logout.OidcClientInitiatedLogoutSuccessHandler;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.core.oidc.user.OidcUserAuthority;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {

    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http, LogoutSuccessHandler oidcLogoutSuccessHandler)
            throws Exception {
        http
            .authorizeHttpRequests(auth -&gt; auth
                .requestMatchers("/", "/public/**").permitAll()
                .anyRequest().authenticated()
            )
            .oauth2Login(oauth2 -&gt; oauth2
                .defaultSuccessUrl("/dashboard", true)
                .userInfoEndpoint(userInfo -&gt; userInfo
                    .userAuthoritiesMapper(keycloakRolesMapper())
                )
            )
            .logout(logout -&gt; logout
                .logoutSuccessHandler(oidcLogoutSuccessHandler)
            );
        return http.build();
    }

    @Bean
    LogoutSuccessHandler oidcLogoutSuccessHandler(ClientRegistrationRepository clientRegistrationRepository) {
        OidcClientInitiatedLogoutSuccessHandler handler =
                new OidcClientInitiatedLogoutSuccessHandler(clientRegistrationRepository);
        handler.setPostLogoutRedirectUri("{baseUrl}/");
        return handler;
    }

    @Bean
    GrantedAuthoritiesMapper keycloakRolesMapper() {
        return authorities -&gt; authorities.stream()
            .flatMap(authority -&gt; {
                if (authority instanceof OidcUserAuthority oidc) {
                    @SuppressWarnings("unchecked")
                    Map&lt;String, Object&gt; resourceAccess = oidc.getIdToken().getClaim("resource_access");
                    if (resourceAccess == null) {
                        return Stream.of(authority);
                    }
                    @SuppressWarnings("unchecked")
                    Map&lt;String, Object&gt; clientAccess =
                            (Map&lt;String, Object&gt;) resourceAccess.get("orders-web");
                    if (clientAccess == null) {
                        return Stream.of(authority);
                    }
                    @SuppressWarnings("unchecked")
                    List&lt;String&gt; roles = (List&lt;String&gt;) clientAccess.get("roles");
                    if (roles == null) {
                        return Stream.of(authority);
                    }
                    return roles.stream()
                        .map(role -&gt; new SimpleGrantedAuthority("ROLE_" + role));
                }
                return Stream.of(authority);
            })
            .collect(Collectors.toSet());
    }
}
</code></pre>
<p>What Spring does for you:</p>
<ul>
<li><p>Generates PKCE <code>code_verifier</code> / <code>code_challenge</code></p>
</li>
<li><p>Sends <code>state</code> and validates it on callback</p>
</li>
<li><p>Exchanges <code>code</code> at <code>/token</code> with client secret (confidential client)</p>
</li>
<li><p>Builds an <code>OAuth2AuthenticationToken</code> with user attributes from ID token / userinfo</p>
</li>
</ul>
<hr />
<h2>Controller</h2>
<p><code>@PreAuthorize</code> on <code>/dashboard</code> checks the mapped client role. The imported realm assigns <code>app-user</code> on <code>orders-web</code> to <code>alice</code> (see the Keycloak post).</p>
<pre><code class="language-java">package info.mnafshin.oauth_demo;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HomeController {

    @GetMapping("/")
    public String home() {
        return "home";
    }

    @GetMapping("/dashboard")
    @PreAuthorize("hasRole('app-user')")
    public String dashboard(@AuthenticationPrincipal OAuth2User principal, Model model) {
        model.addAttribute("name", principal.getAttribute("preferred_username"));
        model.addAttribute("email", principal.getAttribute("email"));
        return "dashboard";
    }
}
</code></pre>
<p>For REST APIs (no server-side session), use <code>oauth2ResourceServer</code> with JWT instead — same series, different starter.</p>
<hr />
<h2>Templates</h2>
<p>The controller returns view names; add Thymeleaf HTML under <code>src/main/resources/templates/</code>.</p>
<p><code>home.html</code>:</p>
<pre><code class="language-html">&lt;!DOCTYPE html&gt;
&lt;html lang="en" xmlns:th="http://www.thymeleaf.org"&gt;
&lt;head&gt;
    &lt;meta charset="UTF-8"&gt;
    &lt;title&gt;OAuth Demo&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;h1&gt;OAuth Demo&lt;/h1&gt;
    &lt;p&gt;A minimal Spring Security OAuth 2.0 login with Keycloak.&lt;/p&gt;
    &lt;p&gt;&lt;a th:href="@{/dashboard}"&gt;Go to dashboard&lt;/a&gt;&lt;/p&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
<p><code>dashboard.html</code> — include a CSRF token on the logout form (Spring Security enables CSRF by default):</p>
<pre><code class="language-html">&lt;!DOCTYPE html&gt;
&lt;html lang="en" xmlns:th="http://www.thymeleaf.org"&gt;
&lt;head&gt;
    &lt;meta charset="UTF-8"&gt;
    &lt;title&gt;Dashboard&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;h1&gt;Dashboard&lt;/h1&gt;
    &lt;p&gt;Hello, &lt;span th:text="${name}"&gt;user&lt;/span&gt;!&lt;/p&gt;
    &lt;p&gt;Email: &lt;span th:text="${email}"&gt;email&lt;/span&gt;&lt;/p&gt;
    &lt;form th:action="@{/logout}" method="post"&gt;
        &lt;input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}"/&gt;
        &lt;button type="submit"&gt;Logout&lt;/button&gt;
    &lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
<p>Without the hidden <code>_csrf</code> field, POST <code>/logout</code> returns <strong>403 Forbidden</strong>. With the OIDC logout handler below, logout also ends the Keycloak SSO session and returns the browser to <code>/</code>.</p>
<hr />
<h2>What Spring Security does <strong>not</strong> do</h2>
<p>Even with <code>oauth2Login</code> working:</p>
<table>
<thead>
<tr>
<th>Still your job</th>
<th>Why</th>
</tr>
</thead>
<tbody><tr>
<td>Map roles from token claims</td>
<td>Spring loads authorities from <code>resource_access</code> only if you add a mapper (shown above)</td>
</tr>
<tr>
<td>Protect downstream APIs</td>
<td>Resource servers need separate JWT validation</td>
</tr>
<tr>
<td>Store refresh tokens safely</td>
<td>Configure <code>OAuth2AuthorizedClientService</code> / JDBC for persistence</td>
</tr>
<tr>
<td>Logout from Keycloak</td>
<td>Use <code>OidcClientInitiatedLogoutSuccessHandler</code> + valid post-logout redirect URI on the client</td>
</tr>
<tr>
<td>Business authorization rules</td>
<td>You define which roles/scopes guard which endpoints (<code>@PreAuthorize</code>, etc.)</td>
</tr>
</tbody></table>
<p>See the identity providers post — the IdP is not the complete solution.</p>
<hr />
<h2>Run locally</h2>
<p>From the repo root:</p>
<pre><code class="language-bash"># Start Keycloak with imported oauth-demo realm (see Keycloak post)
make start-keycloak
# or: docker compose -f modules/keycloak/docker-compose.yml up -d

export KEYCLOAK_CLIENT_SECRET=orders-web-secret
make start-spring-boot
# or: ./gradlew :spring-boot:bootRun
</code></pre>
<p>Each module also has its own <code>Makefile</code> — run <code>make start</code> from <code>modules/spring-boot/</code>.</p>
<ol>
<li><p>Open <code>http://localhost:8080/dashboard</code></p>
</li>
<li><p>Redirect to Keycloak login (user <code>alice</code> / <code>password</code> if using the imported realm)</p>
</li>
<li><p>After login, land on dashboard with username and email — <code>alice</code> has the <code>orders-web</code> client role <code>app-user</code> required by <code>@PreAuthorize</code></p>
</li>
</ol>
<hr />
<h2>Go deeper</h2>
<h3>OAuth2 Authorized Client for calling APIs</h3>
<p>To call a protected API with the user's access token:</p>
<pre><code class="language-java">@GetMapping("/api/proxy/orders")
OAuth2AuthorizedClient authorizedClient(
    @RegisteredOAuth2AuthorizedClient("keycloak") OAuth2AuthorizedClient client) {
    String accessToken = client.getAccessToken().getTokenValue();
    // Use WebClient with Bearer header
}
</code></pre>
<p>Register an <code>OAuth2AuthorizedClientManager</code> bean (Spring Security 6+ — <code>@EnableOAuth2Client</code> was removed).</p>
<h3>Multiple IdPs</h3>
<p>Add another <code>registration</code> (e.g. <code>google</code>, <code>okta</code>) — each gets <code>/login/oauth2/code/{registrationId}</code>.</p>
<h3>Testing</h3>
<p>MockMvc + <code>oauth2Login()</code> from <code>spring-security-test</code> exercises controllers without a live IdP. Because <code>/dashboard</code> uses <code>@PreAuthorize("hasRole('app-user')")</code>, tests must supply <code>ROLE_app-user</code> — login alone is not enough:</p>
<pre><code class="language-java">@SpringBootTest
@AutoConfigureMockMvc
class HomeControllerTest {

    @Autowired MockMvc mockMvc;

    @Test
    void dashboardRequiresAuthentication() throws Exception {
        mockMvc.perform(get("/dashboard"))
            .andExpect(status().is3xxRedirection());
    }

    @Test
    void dashboardRequiresAppUserRole() throws Exception {
        mockMvc.perform(get("/dashboard")
                .with(oauth2Login()
                    .attributes(attrs -&gt; attrs.put("preferred_username", "testuser"))))
            .andExpect(status().isForbidden());
    }

    @Test
    void dashboardShowsAuthenticatedUser() throws Exception {
        mockMvc.perform(get("/dashboard")
                .with(oauth2Login()
                    .authorities(new SimpleGrantedAuthority("ROLE_app-user"))
                    .attributes(attrs -&gt; {
                        attrs.put("preferred_username", "testuser");
                        attrs.put("email", "test@example.com");
                    })))
            .andExpect(status().isOk())
            .andExpect(content().string(containsString("testuser")));
    }

    @Test
    void logoutWithoutCsrfTokenIsRejected() throws Exception {
        mockMvc.perform(post("/logout").with(oauth2Login()))
            .andExpect(status().isForbidden());
    }
}
</code></pre>
<p>For end-to-end login against Keycloak, use Testcontainers or the docker-compose setup from the Keycloak post.</p>
<hr />
<h2>What you should know after this post</h2>
<ul>
<li><p>[ ] You can configure <code>issuer-uri</code> and a Keycloak client in Spring Boot</p>
</li>
<li><p>[ ] You know what Spring auto-handles (PKCE, state, code exchange)</p>
</li>
<li><p>[ ] You can map Keycloak client roles to Spring authorities and guard endpoints with <code>@PreAuthorize</code></p>
</li>
<li><p>[ ] You know what remains manual (API protection as resource server, refresh token storage)</p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[OAuth Mistakes in Production]]></title><description><![CDATA[Every item below appears in real audits. OAuth did not fail — configuration and application code did. Mistake: Register or use open redirectors.]]></description><link>https://springuniverse.hashnode.dev/oauth-mistakes-in-production</link><guid isPermaLink="true">https://springuniverse.hashnode.dev/oauth-mistakes-in-production</guid><dc:creator><![CDATA[Afshin Amini]]></dc:creator><pubDate>Sat, 04 Jul 2026 13:24:29 GMT</pubDate><content:encoded><![CDATA[<h2>This post is a checklist disguised as war stories</h2>
<p>Every item below appears in real audits. OAuth did not fail — configuration and application code did.</p>
<hr />
<h2>1. Redirect URI laxity</h2>
<p><strong>Mistake:</strong> Register <code>https://app.example.com/*</code> or use open redirectors.</p>
<p><strong>Why it hurts:</strong> Authorization codes go to attacker-controlled pages.</p>
<p><strong>Fix:</strong></p>
<ul>
<li><p>Exact match only (scheme, host, port, path)</p>
</li>
<li><p>Separate clients for dev/stage/prod</p>
</li>
<li><p>No wildcard redirect URIs in production</p>
</li>
</ul>
<img src="https://cdn.hashnode.com/uploads/covers/69722030e94f080c107ed87f/b71f63dc-ceb8-4ad8-a363-4d266f9acffa.png" alt="" style="display:block;margin:0 auto" />

<hr />
<h2>2. Missing or weak <code>state</code></h2>
<p><strong>Mistake:</strong> Omit <code>state</code> or use a static value.</p>
<p><strong>Why it hurts:</strong> Login CSRF — victim links attacker's account to victim's session.</p>
<p><strong>Fix:</strong> Cryptographically random <code>state</code>, bound to user agent session, verified on callback.</p>
<hr />
<h2>3. PKCE not enforced</h2>
<p><strong>Mistake:</strong> Public client without PKCE; or <code>code_challenge_method=plain</code>.</p>
<p><strong>Why it hurts:</strong> Stolen authorization codes become tokens.</p>
<p><strong>Fix:</strong> S256 PKCE for all clients; OAuth 2.1 makes this mandatory.</p>
<hr />
<h2>4. Tokens in the wrong place</h2>
<table>
<thead>
<tr>
<th>Token</th>
<th>Never</th>
<th>Prefer</th>
</tr>
</thead>
<tbody><tr>
<td>Refresh token</td>
<td><code>localStorage</code>, mobile logs</td>
<td>Server-side store, httpOnly cookie</td>
</tr>
<tr>
<td>Access token</td>
<td>URL query strings</td>
<td><code>Authorization</code> header</td>
</tr>
<tr>
<td>ID token</td>
<td>Sent to third-party APIs</td>
<td>Client login only</td>
</tr>
</tbody></table>
<p><strong>Mistake:</strong> SPA stores refresh token in <code>localStorage</code> "because it's easier."</p>
<p><strong>Why it hurts:</strong> Any XSS exfiltrates long-lived credentials.</p>
<hr />
<h2>5. Trusting the ID token at the API layer</h2>
<p><strong>Mistake:</strong> Resource server accepts <code>id_token</code> as bearer token.</p>
<p><strong>Why it hurts:</strong> ID token is for the <strong>client</strong>, not your orders API. Wrong audience.</p>
<p><strong>Fix:</strong> APIs require <strong>access tokens</strong> with correct <code>aud</code> (or introspection).</p>
<hr />
<h2>6. JWT validation shortcuts</h2>
<p><strong>Mistake:</strong> Decode JWT, read claims, skip signature verification "in dev."</p>
<p><strong>Why it hurts:</strong> <code>alg: none</code> and key confusion attacks.</p>
<p><strong>Fix:</strong> Always verify:</p>
<ul>
<li><p>Signature (JWKS from <code>iss</code>)</p>
</li>
<li><p><code>exp</code> / <code>nbf</code></p>
</li>
<li><p><code>iss</code> matches expected realm</p>
</li>
<li><p><code>aud</code> contains your API identifier</p>
</li>
<li><p>Scope for the operation</p>
</li>
</ul>
<pre><code class="language-java">// Pseudocode — never hand-roll in production without a library
jwt.verifySignature(jwksUrl)
   .requireIssuer("https://auth.example.com/realms/myrealm")
   .requireAudience("orders-api");
</code></pre>
<hr />
<h2>7. Confusing authentication with authorization</h2>
<p><strong>Mistake:</strong> "User has a valid token" → full admin access.</p>
<p><strong>Fix:</strong> Map IdP identity to <strong>your</strong> roles. Check permissions per resource.</p>
<hr />
<h2>8. One realm to rule them all (badly)</h2>
<p><strong>Mistake:</strong> Dev and prod share a realm; test users in production; admin console on public internet without IP restrict.</p>
<p><strong>Fix:</strong> Environment isolation, least-privilege admin, MFA on IdP admin accounts.</p>
<hr />
<h2>9. Ignoring logout and session drift</h2>
<p><strong>Mistake:</strong> Clear only your app cookie; IdP SSO cookie remains.</p>
<p><strong>Fix:</strong> OIDC end-session endpoint; short access token TTL; refresh rotation.</p>
<hr />
<h2>10. Logging secrets</h2>
<p><strong>Mistake:</strong> Log full token responses, <code>client_secret</code>, <code>code_verifier</code>.</p>
<p><strong>Fix:</strong> Structured logs with token <strong>prefix</strong> only; never log secrets.</p>
<hr />
<h2>Production launch checklist</h2>
<h3>Authorization server (Keycloak / Okta / Auth0)</h3>
<ul>
<li><p>[ ] Production realm / tenant separate from dev</p>
</li>
<li><p>[ ] Redirect URIs exact match per environment</p>
</li>
<li><p>[ ] Client auth method appropriate (secret for confidential, PKCE for public)</p>
</li>
<li><p>[ ] Scopes are minimal (no <code>offline_access</code> unless needed)</p>
</li>
<li><p>[ ] MFA policy defined</p>
</li>
<li><p>[ ] Admin access restricted and audited</p>
</li>
<li><p>[ ] TLS everywhere; HSTS on auth domain</p>
</li>
</ul>
<h3>Application</h3>
<ul>
<li><p>[ ] <code>state</code> validated on every callback</p>
</li>
<li><p>[ ] PKCE S256 on all authorization requests</p>
</li>
<li><p>[ ] Refresh tokens only server-side (or BFF pattern)</p>
</li>
<li><p>[ ] Session cookie: <code>Secure</code>, <code>HttpOnly</code>, <code>SameSite=Lax</code> or <code>Strict</code></p>
</li>
<li><p>[ ] CSRF protection on state-changing endpoints</p>
</li>
<li><p>[ ] Error pages do not leak codes or tokens in HTML</p>
</li>
</ul>
<h3>APIs</h3>
<ul>
<li><p>[ ] Access token validation with full claim checks</p>
</li>
<li><p>[ ] Authorization separate from token presence</p>
</li>
<li><p>[ ] Rate limiting and abuse detection</p>
</li>
<li><p>[ ] Clock skew tolerance configured (~60s)</p>
</li>
</ul>
<h3>Operations</h3>
<ul>
<li><p>[ ] JWKS caching with key rotation support</p>
</li>
<li><p>[ ] Runbook: IdP outage, key rollover, mass revocation</p>
</li>
<li><p>[ ] Alerts on spike in <code>invalid_grant</code>, <code>invalid_client</code></p>
</li>
</ul>
<hr />
<h2>Go deeper</h2>
<h3>Token binding and DPoP</h3>
<p>For high-assurance APIs, consider <strong>Demonstrating Proof-of-Possession (DPoP)</strong> — binds tokens to a client key pair. Supported in some stacks; not universal yet.</p>
<h3>Security headers for SPAs</h3>
<p>Content-Security-Policy, <code>frame-ancestors</code>, no inline scripts — reduces XSS risk that makes token theft possible.</p>
<h3>Penetration test focus areas</h3>
<p>Ask testers to target: redirect manipulation, <code>state</code> bypass, ID token misuse, refresh token replay, and scope escalation.</p>
<hr />
<h2>What you should know after this post</h2>
<ul>
<li><p>[ ] You have a launch checklist copied into your project wiki</p>
</li>
<li><p>[ ] You know the top three browser-side mistakes (redirect, <code>state</code>, storage)</p>
</li>
<li><p>[ ] You validate JWTs completely, not cosmetically</p>
</li>
</ul>
<hr />
]]></content:encoded></item><item><title><![CDATA[Identity Providers Are Not the Complete Solution]]></title><description><![CDATA["We'll buy Okta / Auth0 / deploy Keycloak — then auth is done." Identity providers (IdPs) and authorization servers solve a specific, hard problem: issuing…]]></description><link>https://springuniverse.hashnode.dev/identity-providers-are-not-the-complete-solution</link><guid isPermaLink="true">https://springuniverse.hashnode.dev/identity-providers-are-not-the-complete-solution</guid><dc:creator><![CDATA[Afshin Amini]]></dc:creator><pubDate>Sat, 04 Jul 2026 08:08:43 GMT</pubDate><content:encoded><![CDATA[<h2>The myth</h2>
<blockquote>
<p>"We'll buy Okta / Auth0 / deploy Keycloak — then auth is done."</p>
</blockquote>
<p>Identity providers (IdPs) and authorization servers solve a <strong>specific, hard problem</strong>: issuing tokens after authenticating a user and recording their consent. That is valuable. It is also roughly <strong>30–40%</strong> of a real production auth story.</p>
<p>The rest is still your engineering, your UX, your threat model, and your operations.</p>
<hr />
<h2>What Keycloak / Okta / Auth0 actually give you</h2>
<table>
<thead>
<tr>
<th>Capability</th>
<th>Keycloak (self-hosted)</th>
<th>Okta / Auth0 (managed)</th>
</tr>
</thead>
<tbody><tr>
<td>User directory (or federation hook)</td>
<td>Built-in + LDAP/AD</td>
<td>Built-in + federation</td>
</tr>
<tr>
<td>OIDC/OAuth endpoints</td>
<td>Yes</td>
<td>Yes</td>
</tr>
<tr>
<td>Admin UI for clients, scopes, roles</td>
<td>Yes</td>
<td>Yes</td>
</tr>
<tr>
<td>Social / enterprise IdP federation</td>
<td>Yes (brokers)</td>
<td>Yes (core product)</td>
</tr>
<tr>
<td>MFA policies</td>
<td>Yes</td>
<td>Yes (often stronger UX)</td>
</tr>
<tr>
<td>Hosted login pages</td>
<td>Themes (you customize)</td>
<td>Hosted, customizable</td>
</tr>
<tr>
<td>Compliance certifications</td>
<td>Your infra responsibility</td>
<td>Vendor SOC2/ISO etc.</td>
</tr>
</tbody></table>
<p><strong>You are buying:</strong> a standards-compliant authorization server, user store or federation point, and token minting.</p>
<p><strong>You are not buying:</strong> a finished application security layer.</p>
<hr />
<h2>What you still must build (the other 60–70%)</h2>
<h3>1. Application integration</h3>
<ul>
<li><p>Register every client (<code>client_id</code>, redirect URIs, scopes)</p>
</li>
<li><p>Configure Spring Security / your framework (covered in the Spring Security hands-on post)</p>
</li>
<li><p>Map IdP groups → application roles</p>
</li>
<li><p>Handle token validation on <strong>your</strong> APIs</p>
</li>
</ul>
<h3>2. UX beyond the login button</h3>
<ul>
<li><p>Landing pages, error states, account linking</p>
</li>
<li><p>"Session expired" and silent refresh behavior</p>
</li>
<li><p>Consent copy users actually understand</p>
</li>
<li><p>Branding that matches your product (Keycloak themes or Okta hosted pages)</p>
</li>
</ul>
<h3>3. Authorization inside your app</h3>
<p>OAuth scopes ≠ your business permissions.</p>
<img src="https://cdn.hashnode.com/uploads/covers/69722030e94f080c107ed87f/d5582c2f-81e0-4cdc-aca1-62c47bb320a2.png" alt="" style="display:block;margin:0 auto" />

<p>You need an authorization model (RBAC, ABAC, row-level security) in <strong>your</strong> services.</p>
<h3>4. Session strategy</h3>
<p>After OIDC login, what does the browser hold?</p>
<table>
<thead>
<tr>
<th>Pattern</th>
<th>Pros</th>
<th>Cons</th>
</tr>
</thead>
<tbody><tr>
<td>Server session + httpOnly cookie</td>
<td>Refresh token never in JS</td>
<td>Needs sticky sessions or shared store</td>
</tr>
<tr>
<td>BFF with cookie</td>
<td>Good for SPAs</td>
<td>Extra service to run</td>
</tr>
<tr>
<td>Tokens in SPA memory</td>
<td>Simple demo</td>
<td>XSS = token theft</td>
</tr>
</tbody></table>
<p>The IdP does not choose this for you.</p>
<h3>5. API and microservice security</h3>
<ul>
<li><p>Validate JWTs (signature, <code>iss</code>, <code>aud</code>, <code>exp</code>, <code>nbf</code>)</p>
</li>
<li><p>Service-to-service auth (client credentials, mTLS)</p>
</li>
<li><p>Token propagation vs token exchange between services</p>
</li>
<li><p>Centralized policy (OPA, custom) vs per-service checks</p>
</li>
</ul>
<h3>6. Operational work</h3>
<p><strong>Keycloak (self-hosted):</strong></p>
<ul>
<li><p>HA deployment, database backups, upgrades</p>
</li>
<li><p>Realm configuration across environments (dev/stage/prod)</p>
</li>
<li><p>Secret rotation, TLS, network policies</p>
</li>
<li><p>Monitoring failed logins, brute force, token errors</p>
</li>
</ul>
<p><strong>Okta / Auth0 (managed):</strong></p>
<ul>
<li><p>Still: environment promotion, Terraform, rate limits, pricing tiers</p>
</li>
<li><p>Custom domains, email templates, support runbooks</p>
</li>
<li><p>Exit strategy / vendor lock-in considerations</p>
</li>
</ul>
<h3>7. User lifecycle</h3>
<ul>
<li><p>Registration, invite flows, password reset (if local users)</p>
</li>
<li><p>HR offboarding → disable user in IdP <strong>and</strong> revoke app sessions</p>
</li>
<li><p>Account merging, duplicate emails, guest users</p>
</li>
</ul>
<h3>8. Compliance and audit</h3>
<ul>
<li><p>Who accessed what, when — in <strong>your</strong> audit logs</p>
</li>
<li><p>Data residency (where Keycloak DB lives; Okta tenant region)</p>
</li>
<li><p>PII in JWT claims (minimize what you put in tokens)</p>
</li>
</ul>
<hr />
<h2>Responsibility split (diagram)</h2>
<img src="https://cdn.hashnode.com/uploads/covers/69722030e94f080c107ed87f/08fd297f-bcee-48fc-b07e-04acd9149208.png" alt="" style="display:block;margin:0 auto" />

<hr />
<h2>Keycloak vs Okta vs Auth0 — how to think about the buy</h2>
<table>
<thead>
<tr>
<th>Factor</th>
<th>Keycloak</th>
<th>Okta / Auth0</th>
</tr>
</thead>
<tbody><tr>
<td>Cost model</td>
<td>Infra + your ops time</td>
<td>Per MAU / feature tier</td>
</tr>
<tr>
<td>Control</td>
<td>Full (you patch the server)</td>
<td>Limited to vendor features</td>
</tr>
<tr>
<td>Time to first login</td>
<td>Days (if you know K8s)</td>
<td>Hours</td>
</tr>
<tr>
<td>Customization</td>
<td>Deep (SPIs, themes)</td>
<td>Themed hosted pages</td>
</tr>
<tr>
<td>Best when</td>
<td>Cost at scale, on-prem, air-gap</td>
<td>Small team, fast ship, compliance via vendor</td>
</tr>
</tbody></table>
<p>None of them removes the <strong>your responsibility</strong> box above.</p>
<hr />
<h2>Anti-patterns we see in production</h2>
<ol>
<li><p><strong>"Keycloak is our auth"</strong> — but no service validates JWTs; anyone with a forged cookie gets in.</p>
</li>
<li><p><strong>Giant JWT</strong> — stuffing every permission into the token; exceeds header limits and leaks data.</p>
</li>
<li><p><strong>Same client for SPA and mobile</strong> — different redirect URI and PKCE rules get mixed.</p>
</li>
<li><p><strong>Prod realm cloned from dev</strong> — with test users and wildcard redirect URIs still enabled.</p>
</li>
<li><p><strong>No logout story</strong> — IdP SSO session remains; user thinks they logged out.</p>
</li>
</ol>
<hr />
<h2>Go deeper</h2>
<h3>Infrastructure as code</h3>
<p>Treat realms, clients, and scopes as code (Keycloak Terraform provider, Okta Terraform, Auth0 deploy CLI). Manual admin UI clicks do not survive three environments.</p>
<h3>Multi-region and DR</h3>
<p>Keycloak: database replication, stateful session considerations. Managed IdPs: read their SLA and data residency docs — still <strong>your</strong> failover runbook for what happens when IdP is down (read-only mode? maintenance page?).</p>
<h3>When to add an API gateway</h3>
<p>Gateways can validate JWTs centrally. You still need fine-grained authorization in services — gateways are not a substitute.</p>
<hr />
<h2>What you should know after this post</h2>
<ul>
<li><p>[ ] You can list at least five things an IdP does <strong>not</strong> do for you</p>
</li>
<li><p>[ ] You separate OAuth scopes from application-level permissions</p>
</li>
<li><p>[ ] You have a realistic view of Keycloak ops vs Okta convenience</p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Authorization Code + PKCE]]></title><description><![CDATA[If you implement only one OAuth flow, make it Authorization Code with PKCE (Proof Key for Code Exchange). It works for: Server-side web apps (Spring Boot…]]></description><link>https://springuniverse.hashnode.dev/authorization-code-pkce</link><guid isPermaLink="true">https://springuniverse.hashnode.dev/authorization-code-pkce</guid><dc:creator><![CDATA[Afshin Amini]]></dc:creator><pubDate>Thu, 02 Jul 2026 23:27:31 GMT</pubDate><content:encoded><![CDATA[<h2>The one flow to learn first</h2>
<p>If you implement only one OAuth flow, make it <strong>Authorization Code with PKCE</strong> (Proof Key for Code Exchange).</p>
<p>It works for:</p>
<ul>
<li><p>Server-side web apps (Spring Boot, Django, Rails)</p>
</li>
<li><p>Single-page applications (React, Vue)</p>
</li>
<li><p>Mobile apps (iOS, Android)</p>
</li>
</ul>
<p>The older <strong>implicit</strong> flow put access tokens in the URL fragment. That is deprecated. Password grant bypasses consent. Auth Code + PKCE is the 2026 default.</p>
<hr />
<h2>Step-by-step (with real parameters)</h2>
<img src="https://cdn.hashnode.com/uploads/covers/69722030e94f080c107ed87f/4ed13fa3-13eb-4a1c-ae93-98d9e4988739.png" alt="" style="display:block;margin:0 auto" />

<hr />
<h2>What each step does</h2>
<h3>Step 1 — Authorization request</h3>
<p>The client redirects the user to the authorization server. Critical query parameters:</p>
<table>
<thead>
<tr>
<th>Parameter</th>
<th>Purpose</th>
</tr>
</thead>
<tbody><tr>
<td><code>response_type=code</code></td>
<td>"I want an authorization code"</td>
</tr>
<tr>
<td><code>client_id</code></td>
<td>Identifies your registered app</td>
</tr>
<tr>
<td><code>redirect_uri</code></td>
<td>Must <strong>exactly</strong> match a registered URI</td>
</tr>
<tr>
<td><code>scope</code></td>
<td>Requested permissions (<code>openid</code> triggers OIDC)</td>
</tr>
<tr>
<td><code>state</code></td>
<td>CSRF protection — random, stored server-side or in session</td>
</tr>
<tr>
<td><code>code_challenge</code></td>
<td>PKCE: hash of a secret the client will prove later</td>
</tr>
<tr>
<td><code>code_challenge_method=S256</code></td>
<td>SHA-256 (not <code>plain</code>)</td>
</tr>
</tbody></table>
<p>Example URL (formatted for reading):</p>
<pre><code class="language-text">https://auth.example.com/realms/myrealm/protocol/openid-connect/auth
  ?response_type=code
  &amp;client_id=orders-web
  &amp;redirect_uri=https%3A%2F%2Fapp.example.com%2Flogin%2Foauth2%2Fcode%2Fkeycloak
  &amp;scope=openid%20profile%20email
  &amp;state=8f3c2a1b
  &amp;code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM
  &amp;code_challenge_method=S256
</code></pre>
<h3>Step 2 — Authorization code in redirect</h3>
<p>On success, the user agent is redirected to your <code>redirect_uri</code>:</p>
<pre><code class="language-text">https://app.example.com/login/oauth2/code/keycloak
  ?code=0.AX4A...truncated...
  &amp;state=8f3c2a1b
</code></pre>
<p><strong>Your code must:</strong></p>
<ol>
<li><p>Verify <code>state</code> matches what you stored</p>
</li>
<li><p>Reject missing or tampered <code>state</code></p>
</li>
<li><p>Exchange <code>code</code> promptly (codes are short-lived, often ~60 seconds)</p>
</li>
</ol>
<p>The code is useless without the PKCE verifier (and, for confidential clients, without the client secret).</p>
<h3>Step 3 — Token request</h3>
<p>Backend (or SPA with caution) POSTs to <code>/token</code>:</p>
<pre><code class="language-http">POST /realms/myrealm/protocol/openid-connect/token HTTP/1.1
Host: auth.example.com
Content-Type: application/x-www-form-urlencoded

grant_type=authorization_code
&amp;code=0.AX4A...
&amp;redirect_uri=https://app.example.com/login/oauth2/code/keycloak
&amp;client_id=orders-web
&amp;code_verifier=dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk
</code></pre>
<p>For <strong>confidential</strong> clients (server-side Spring app), also send <code>client_secret</code> or use client authentication via JWT assertion.</p>
<h3>Step 4 — Token response</h3>
<pre><code class="language-json">{
  "access_token": "eyJhbGciOiJSUzI1NiIs...",
  "expires_in": 300,
  "refresh_expires_in": 1800,
  "refresh_token": "eyJhbGciOiJIUzUxMiIs...",
  "token_type": "Bearer",
  "id_token": "eyJhbGciOiJSUzI1NiIs...",
  "scope": "openid profile email"
}
</code></pre>
<h3>Step 5–6 — Call the API</h3>
<pre><code class="language-http">GET /api/orders HTTP/1.1
Host: api.example.com
Authorization: Bearer eyJhbGciOiJSUzI1NiIs...
</code></pre>
<p>The resource server validates signature, expiry, issuer, audience, and scopes.</p>
<hr />
<h2>PKCE in plain language</h2>
<p><strong>Problem:</strong> Public clients (SPA, mobile) cannot hide a <code>client_secret</code>. An attacker who steals an authorization <code>code</code> could exchange it for tokens.</p>
<p><strong>PKCE fix:</strong></p>
<ol>
<li><p>Client generates random <code>code_verifier</code> (43–128 chars)</p>
</li>
<li><p>Sends <code>code_challenge = BASE64URL(SHA256(code_verifier))</code> in step 1</p>
</li>
<li><p>Proves possession by sending <code>code_verifier</code> in step 3</p>
</li>
</ol>
<p>Only the client that started the flow can finish it.</p>
<pre><code class="language-java">// Generating PKCE values (conceptual)
String codeVerifier = secureRandomBase64Url(64);
String codeChallenge = base64Url(sha256(codeVerifier));
</code></pre>
<p>Even confidential server apps should send PKCE today (OAuth 2.1 direction).</p>
<hr />
<h2>Confidential vs public clients</h2>
<table>
<thead>
<tr>
<th></th>
<th>Confidential</th>
<th>Public</th>
</tr>
</thead>
<tbody><tr>
<td>Examples</td>
<td>Spring Boot server, backend API</td>
<td>SPA, mobile app</td>
</tr>
<tr>
<td>Secret</td>
<td>Has <code>client_secret</code></td>
<td>No secret</td>
</tr>
<tr>
<td>Token exchange</td>
<td>Backend channel</td>
<td>Backend-for-frontend recommended</td>
</tr>
<tr>
<td>PKCE</td>
<td>Recommended</td>
<td>Required</td>
</tr>
</tbody></table>
<p><strong>For SPAs:</strong> do not put <code>client_secret</code> in JavaScript. Use a backend-for-frontend (BFF) or the SPA pattern with strict origin + short-lived tokens + refresh via httpOnly cookie.</p>
<hr />
<h2>Refresh flow (when access token expires)</h2>
<pre><code class="language-http">POST /token
grant_type=refresh_token
&amp;refresh_token=eyJhbGciOiJIUzUxMiIs...
&amp;client_id=orders-web
</code></pre>
<p>Returns a new access token (and sometimes a rotated refresh token). Handle refresh <strong>server-side</strong> when possible.</p>
<hr />
<h2>Go deeper</h2>
<h3>PAR and JAR (optional hardening)</h3>
<ul>
<li><p><strong>Pushed Authorization Requests (PAR):</strong> send authorize parameters via back-channel POST first, get <code>request_uri</code></p>
</li>
<li><p><strong>JWT Secured Authorization Request (JAR):</strong> signed request objects</p>
</li>
</ul>
<p>Useful in high-security environments; Keycloak supports PAR in recent versions.</p>
<h3>Logout</h3>
<p>OAuth does not standardize logout completely. OIDC provides:</p>
<ul>
<li><p><strong>RP-initiated logout</strong> — redirect to <code>end_session_endpoint</code></p>
</li>
<li><p><strong>Front-channel / back-channel logout</strong> — SSO session termination</p>
</li>
</ul>
<p>Plan logout explicitly; closing your app cookie alone may leave an IdP SSO session alive.</p>
<h3>Discovery document</h3>
<p>Fetch once at startup:</p>
<pre><code class="language-text">GET https://auth.example.com/realms/myrealm/.well-known/openid-configuration
</code></pre>
<p>Contains endpoints for authorize, token, jwks, userinfo, end_session. Spring and Keycloak clients use this automatically.</p>
<hr />
<h2>What you should know after this post</h2>
<ul>
<li><p>[ ] You can draw the six steps from memory</p>
</li>
<li><p>[ ] You know why <code>state</code> and PKCE matter</p>
</li>
<li><p>[ ] You never put refresh tokens in browser <code>localStorage</code></p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[The OAuth Mental Model]]></title><description><![CDATA[OAuth names four actors. Everything else hangs off them. One company often runs both authorization server and resource server (Google issues tokens and…]]></description><link>https://springuniverse.hashnode.dev/the-oauth-mental-model</link><guid isPermaLink="true">https://springuniverse.hashnode.dev/the-oauth-mental-model</guid><dc:creator><![CDATA[Afshin Amini]]></dc:creator><pubDate>Tue, 30 Jun 2026 04:22:50 GMT</pubDate><content:encoded><![CDATA[<h2>Four roles (memorize these)</h2>
<p>OAuth names four actors. Everything else hangs off them.</p>
<img src="https://cdn.hashnode.com/uploads/covers/69722030e94f080c107ed87f/ce59fa9f-6043-4a05-b228-263ed7b26212.png" alt="" style="display:block;margin:0 auto" />

<table>
<thead>
<tr>
<th>Role</th>
<th>Plain English</th>
<th>Example</th>
</tr>
</thead>
<tbody><tr>
<td><strong>Resource owner</strong></td>
<td>User who can grant access</td>
<td>Alice</td>
</tr>
<tr>
<td><strong>Client</strong></td>
<td>App requesting access</td>
<td>Your Spring Boot app</td>
</tr>
<tr>
<td><strong>Authorization server</strong></td>
<td>Issues tokens after consent</td>
<td>Keycloak realm</td>
</tr>
<tr>
<td><strong>Resource server</strong></td>
<td>API that accepts tokens</td>
<td>Your <code>/api/orders</code> service</td>
</tr>
</tbody></table>
<p>One company often runs <strong>both</strong> authorization server and resource server (Google issues tokens and hosts Gmail API). In microservices, they are usually separate.</p>
<hr />
<h2>Three token types you will meet</h2>
<h3>Access token</h3>
<ul>
<li><p><strong>Purpose:</strong> Prove authorization to call an API</p>
</li>
<li><p><strong>Audience:</strong> Resource server</p>
</li>
<li><p><strong>Format:</strong> Often opaque or JWT</p>
</li>
<li><p><strong>Lifetime:</strong> Short (minutes to an hour)</p>
</li>
</ul>
<pre><code class="language-http">GET /api/orders HTTP/1.1
Host: api.example.com
Authorization: Bearer eyJhbGciOiJSUzI1NiIs...
</code></pre>
<h3>Refresh token</h3>
<ul>
<li><p><strong>Purpose:</strong> Obtain a new access token without re-prompting the user</p>
</li>
<li><p><strong>Audience:</strong> Authorization server only</p>
</li>
<li><p><strong>Lifetime:</strong> Longer (days/weeks), revocable</p>
</li>
<li><p><strong>Storage:</strong> Server-side or secure httpOnly cookie — <strong>never</strong> <code>localStorage</code> in a browser</p>
</li>
</ul>
<h3>ID token (OIDC, not pure OAuth)</h3>
<ul>
<li><p><strong>Purpose:</strong> Identity claims about the authenticated user</p>
</li>
<li><p><strong>Audience:</strong> Client application</p>
</li>
<li><p><strong>Format:</strong> JWT</p>
</li>
<li><p><strong>Lifetime:</strong> Short; not an API credential</p>
</li>
</ul>
<p><strong>Rule of thumb:</strong> Use the <strong>access token</strong> for APIs. Use the <strong>ID token</strong> for login/session identity in your client.</p>
<hr />
<h2>Scopes: the valet key notches</h2>
<p>Scopes limit what a token can do. They are strings agreed between client and authorization server.</p>
<pre><code class="language-text">openid profile email
read:orders write:orders
</code></pre>
<table>
<thead>
<tr>
<th>Scope</th>
<th>Meaning</th>
</tr>
</thead>
<tbody><tr>
<td><code>openid</code></td>
<td>OIDC request — return an ID token</td>
</tr>
<tr>
<td><code>profile</code></td>
<td>Name, picture, etc.</td>
</tr>
<tr>
<td><code>email</code></td>
<td>Email address</td>
</tr>
<tr>
<td><code>read:orders</code></td>
<td>Custom API scope (you define in Keycloak)</td>
</tr>
</tbody></table>
<p>The authorization server shows the user a <strong>consent screen</strong> listing scopes. The issued access token embeds (or maps to) only approved scopes.</p>
<hr />
<h2>Flows = how the client gets tokens</h2>
<p>A <strong>grant type</strong> (flow) is the protocol path from "user wants to use app" to "client holds tokens."</p>
<table>
<thead>
<tr>
<th>Flow</th>
<th>Use today?</th>
<th>Notes</th>
</tr>
</thead>
<tbody><tr>
<td><strong>Authorization Code + PKCE</strong></td>
<td><strong>Yes — default</strong></td>
<td>SPAs, mobile, server apps</td>
</tr>
<tr>
<td>Client credentials</td>
<td>Yes</td>
<td>Machine-to-machine, no user</td>
</tr>
<tr>
<td>Device code</td>
<td>Yes</td>
<td>TVs, CLI devices</td>
</tr>
<tr>
<td>Implicit</td>
<td><strong>No</strong></td>
<td>Replaced by Auth Code + PKCE</td>
</tr>
<tr>
<td>Resource owner password</td>
<td><strong>No</strong></td>
<td>Deprecated; bypasses consent</td>
</tr>
</tbody></table>
<p>A later post in this series walks through Authorization Code + PKCE in detail.</p>
<hr />
<h2>OIDC sits on top of OAuth</h2>
<img src="https://cdn.hashnode.com/uploads/covers/69722030e94f080c107ed87f/114e6631-2c2e-491c-9da6-954fca98f357.png" alt="" style="display:block;margin:0 auto" />

<p>OIDC adds:</p>
<ul>
<li><p><code>id_token</code> JWT</p>
</li>
<li><p><code>/userinfo</code> endpoint</p>
</li>
<li><p>Discovery document at <code>/.well-known/openid-configuration</code></p>
</li>
</ul>
<p>When people say "OAuth login," they almost always mean <strong>OIDC</strong>.</p>
<hr />
<h2>Sessions vs tokens (where confusion starts)</h2>
<table>
<thead>
<tr>
<th>Concept</th>
<th>Where it lives</th>
<th>Typical use</th>
</tr>
</thead>
<tbody><tr>
<td>OAuth tokens</td>
<td>Client + auth server contract</td>
<td>API access</td>
</tr>
<tr>
<td>App session</td>
<td>Your server or cookie</td>
<td>"Logged in to <em>our</em> app"</td>
</tr>
</tbody></table>
<p>A common pattern:</p>
<ol>
<li><p>User completes OIDC flow → your backend receives tokens</p>
</li>
<li><p>Backend validates ID token, creates <strong>app session</strong> (cookie)</p>
</li>
<li><p>Backend stores refresh token server-side</p>
</li>
<li><p>Browser only sees session cookie; never holds refresh token</p>
</li>
</ol>
<p>Your app still needs session management. OAuth does not replace it.</p>
<hr />
<h2>Go deeper</h2>
<h3>JWT access tokens vs opaque tokens</h3>
<p><strong>JWT (self-contained):</strong></p>
<ul>
<li><p>Resource server can validate locally (signature + claims)</p>
</li>
<li><p>Harder to revoke instantly</p>
</li>
<li><p>Must keep claims small</p>
</li>
</ul>
<p><strong>Opaque:</strong></p>
<ul>
<li><p>Resource server introspects with auth server</p>
</li>
<li><p>Revocation is immediate</p>
</li>
<li><p>Extra network hop</p>
</li>
</ul>
<p>Keycloak can do both. Choose based on revocation needs and API topology.</p>
<h3>Audience (<code>aud</code>) and issuer (<code>iss</code>)</h3>
<p>JWTs carry <code>iss</code> (who minted) and <code>aud</code> (who may consume). Validating only the signature without checking <code>aud</code> is a common vulnerability — your API must reject tokens minted for a different client.</p>
<h3>Multi-tenant mental model</h3>
<p>In Keycloak:</p>
<ul>
<li><p><strong>Realm</strong> ≈ tenant</p>
</li>
<li><p><strong>Client</strong> ≈ your application registration</p>
</li>
<li><p><strong>Users</strong> live in the realm</p>
</li>
</ul>
<p>Okta/Auth0 use different names (Authorization Server, Application) but the same idea: you register your app and get <code>client_id</code> + credentials.</p>
<hr />
<h2>What you should know after this post</h2>
<ul>
<li><p>[ ] You can name all four roles and one example of each</p>
</li>
<li><p>[ ] You know access vs refresh vs ID token</p>
</li>
<li><p>[ ] You default to Authorization Code + PKCE for user-facing clients</p>
</li>
<li><p>[ ] You separate "OAuth tokens" from "my app's session"</p>
</li>
</ul>
<hr />
]]></content:encoded></item><item><title><![CDATA[Why OAuth Exists]]></title><description><![CDATA[Your application wants to access a user's data on another service — their Google Calendar, GitHub repositories, or company files in SharePoint. The naive…]]></description><link>https://springuniverse.hashnode.dev/why-oauth-exists</link><guid isPermaLink="true">https://springuniverse.hashnode.dev/why-oauth-exists</guid><dc:creator><![CDATA[Afshin Amini]]></dc:creator><pubDate>Tue, 30 Jun 2026 04:13:33 GMT</pubDate><content:encoded><![CDATA[<h2>The scenario everyone recognizes</h2>
<p>Your application wants to access a user's data on another service — their Google Calendar, GitHub repositories, or company files in SharePoint.</p>
<p>The naive approach: ask for their password.</p>
<img src="https://cdn.hashnode.com/uploads/covers/69722030e94f080c107ed87f/c155efc1-3f77-44b9-85d4-d0dddc3ed68a.png" alt="" style="display:block;margin:0 auto" />

<p>That fails for obvious reasons:</p>
<ol>
<li><p><strong>Trust</strong> — the user must fully trust your app with their primary credentials.</p>
</li>
<li><p><strong>Scope</strong> — you get <em>all</em> access, not just calendar read.</p>
</li>
<li><p><strong>Revocation</strong> — changing the Google password breaks your app <em>and</em> every other service.</p>
</li>
<li><p><strong>Audit</strong> — Google cannot tell "the user logged in" from "YourApp logged in on their behalf."</p>
</li>
</ol>
<p>OAuth exists to fix this. Its core idea is <strong>delegated authorization</strong>: the user grants your application limited permission without handing over their password.</p>
<hr />
<h2>What OAuth is (one sentence)</h2>
<blockquote>
<p>OAuth lets a user authorize a third-party application to access their resources on a resource server, without sharing their credentials with that application.</p>
</blockquote>
<p>Notice what is <em>not</em> in that sentence: "login," "identity," or "authentication."</p>
<p>OAuth is primarily an <strong>authorization</strong> framework. In practice we use it for login because "who approved this access?" implies "who is this person?" — but that identity layer (OpenID Connect) is a separate spec built on top of OAuth 2.0.</p>
<hr />
<h2>A durable analogy: the valet key</h2>
<p>When you valet park, you do not hand over your house keys. You hand over a <strong>valet key</strong> that:</p>
<ul>
<li><p>starts the car</p>
</li>
<li><p>does <strong>not</strong> open the glove box or trunk (unless the manufacturer allows it)</p>
</li>
<li><p>can be collected when you leave</p>
</li>
</ul>
<p>OAuth access tokens work the same way:</p>
<table>
<thead>
<tr>
<th>Real world</th>
<th>OAuth</th>
</tr>
</thead>
<tbody><tr>
<td>You (car owner)</td>
<td>Resource owner (user)</td>
</tr>
<tr>
<td>Valet company</td>
<td>Client application</td>
</tr>
<tr>
<td>Car manufacturer key system</td>
<td>Authorization server</td>
</tr>
<tr>
<td>Your car</td>
<td>Resource server (API)</td>
</tr>
<tr>
<td>Valet key</td>
<td>Access token</td>
</tr>
</tbody></table>
<p>The valet never learns your main key. Your app never learns the user's Google password.</p>
<hr />
<h2>The problem OAuth does <strong>not</strong> solve</h2>
<p>OAuth is not a silver bullet. It does <strong>not</strong>:</p>
<ul>
<li><p>Replace your application's <strong>authorization</strong> (what roles can do inside <em>your</em> app)</p>
</li>
<li><p>Eliminate the need for <strong>secure coding</strong> (XSS, CSRF, SSRF still matter)</p>
</li>
<li><p>Choose your <strong>user directory</strong> (LDAP, database, social login — you still decide)</p>
</li>
<li><p>Ship a finished <strong>login UI</strong> (you build or embed consent screens)</p>
</li>
<li><p>Handle <strong>compliance</strong> by itself (GDPR, SOC2, retention — still your process)</p>
</li>
</ul>
<p>Buying Keycloak, Okta, or Auth0 gives you a strong authorization server — not a finished product.</p>
<hr />
<h2>A brief history (why there are so many terms)</h2>
<table>
<thead>
<tr>
<th>Era</th>
<th>What happened</th>
</tr>
</thead>
<tbody><tr>
<td>OAuth 1.0a</td>
<td>HMAC signatures, painful for mobile/SPA</td>
</tr>
<tr>
<td>OAuth 2.0 (2012)</td>
<td>Simpler bearer tokens; multiple "grant types"</td>
</tr>
<tr>
<td>OAuth 2.1 (draft)</td>
<td>Community cleanup: PKCE everywhere, deprecate risky grants</td>
</tr>
<tr>
<td>OpenID Connect (OIDC)</td>
<td>Standardized identity layer on OAuth 2.0</td>
</tr>
</tbody></table>
<p>You do not need OAuth 1.0a for new work. This series focuses on <strong>OAuth 2.0 + OIDC</strong>, with <strong>Authorization Code + PKCE</strong> as the only flow you should implement for user-facing apps.</p>
<hr />
<h2>When to reach for OAuth</h2>
<table>
<thead>
<tr>
<th>Situation</th>
<th>OAuth?</th>
</tr>
</thead>
<tbody><tr>
<td>User signs in via Google/GitHub/company SSO</td>
<td>Yes</td>
</tr>
<tr>
<td>Your SPA calls an API on behalf of a logged-in user</td>
<td>Yes</td>
</tr>
<tr>
<td>Server-to-server batch job with no user</td>
<td>Different pattern (client credentials)</td>
</tr>
<tr>
<td>Two microservices inside your VPC</td>
<td>Often mutual TLS or internal IAM, not user OAuth</td>
</tr>
<tr>
<td>"Remember me" inside your own monolith</td>
<td>Session cookies may be enough</td>
</tr>
</tbody></table>
<hr />
<h2>Go deeper</h2>
<h3>Resource owner vs client vs authorization server</h3>
<p>Even in "Login with Google," three parties exist:</p>
<ul>
<li><p><strong>Google</strong> (authorization + resource server for Google APIs)</p>
</li>
<li><p><strong>Your app</strong> (client)</p>
</li>
<li><p><strong>The user</strong> (resource owner)</p>
</li>
</ul>
<p>Your app receives a token <strong>about</strong> the user, not <strong>from</strong> the user directly.</p>
<h3>Why "OAuth for login" took over</h3>
<p>Before OIDC, every provider returned different user profile JSON. OIDC standardizes:</p>
<ul>
<li><p>an <code>id_token</code> (JWT with identity claims)</p>
</li>
<li><p>a <code>/userinfo</code> endpoint</p>
</li>
<li><p>discovery via <code>/.well-known/openid-configuration</code></p>
</li>
</ul>
<p>So "OAuth login" in 2026 really means <strong>OIDC on top of OAuth 2.0</strong>.</p>
<h3>OAuth vs API keys</h3>
<p>API keys identify the <strong>application</strong>, not a <strong>user on behalf of whom</strong> the app acts. OAuth adds user consent and scoped, revocable delegation.</p>
<hr />
<h2>What you should know after this post</h2>
<ul>
<li><p>[ ] You can explain delegated authorization without saying "it's login"</p>
</li>
<li><p>[ ] You know why sharing passwords is the anti-pattern</p>
</li>
<li><p>[ ] You recognize OAuth solves <strong>access to resources</strong>, not your entire security model</p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Stop Inventing Error JSON: A Practical Guide to RFC 7807 Problem Details]]></title><description><![CDATA[Every HTTP API eventually returns an error. The hard part is not the status code — it is the body. One service returns { "error": "not found" }, another…]]></description><link>https://springuniverse.hashnode.dev/stop-inventing-error-json-a-practical-guide-to-rfc-7807-problem-details</link><guid isPermaLink="true">https://springuniverse.hashnode.dev/stop-inventing-error-json-a-practical-guide-to-rfc-7807-problem-details</guid><dc:creator><![CDATA[Afshin Amini]]></dc:creator><pubDate>Mon, 29 Jun 2026 23:02:50 GMT</pubDate><content:encoded><![CDATA[<p>Every HTTP API eventually returns an error. The hard part is not the status code — it is the body. One service returns <code>{ "error": "not found" }</code>, another returns <code>{ "message": "User does not exist" }</code>, and a third serves HTML from a reverse proxy. Clients end up with fragile <code>if (body.error)</code> logic that breaks the moment they call a second API.</p>
<p><a href="https://www.rfc-editor.org/rfc/rfc7807.html">RFC 7807</a> fixes that by defining a small, standard JSON object for error responses: <strong>Problem Details</strong>. The idea is simple: keep HTTP status codes as the primary signal, and put structured, machine-readable context in the body.</p>
<blockquote>
<p>RFC 7807 was superseded by <a href="https://www.rfc-editor.org/rfc/rfc9457.html">RFC 9457</a> in 2023. The field names and overall shape are the same. This post uses "RFC 7807" because that is still the name most teams search for.</p>
</blockquote>
<p><strong>Companion repository:</strong> <a href="https://github.com/mnafshin/RFC_7807">github.com/mnafshin/RFC_7807</a> — a runnable Spring Boot demo with OpenAPI SSOT, Problem Detail error handling, and integration tests. Clone it and follow along:</p>
<pre><code class="language-bash">git clone https://github.com/mnafshin/RFC_7807.git
cd RFC_7807
./gradlew test
</code></pre>
<h2>What a Problem Detail looks like</h2>
<p>A Problem Detail is a JSON object with a few well-known fields:</p>
<table>
<thead>
<tr>
<th>Field</th>
<th>Meaning</th>
</tr>
</thead>
<tbody><tr>
<td><code>type</code></td>
<td>URI identifying the <em>category</em> of problem</td>
</tr>
<tr>
<td><code>title</code></td>
<td>Short, stable summary of that category</td>
</tr>
<tr>
<td><code>status</code></td>
<td>HTTP status code for this occurrence</td>
</tr>
<tr>
<td><code>detail</code></td>
<td>Explanation specific to <em>this</em> request</td>
</tr>
<tr>
<td><code>instance</code></td>
<td>URI identifying this specific error occurrence</td>
</tr>
</tbody></table>
<p>The response uses the <code>application/problem+json</code> media type.</p>
<p>Here is a realistic example — a withdrawal rejected because the account does not have enough credits:</p>
<pre><code class="language-http">HTTP/1.1 403 Forbidden
Content-Type: application/problem+json

{
  "type": "https://problem-detail-demo.mnafshin.info/problems/insufficient-balance",
  "title": "Insufficient balance",
  "status": 403,
  "detail": "Account 123 has 30 credits but this operation costs 50",
  "instance": "/accounts/123/withdraw",
  "accountId": "123",
  "balance": 30,
  "required": 50
}
</code></pre>
<p>Notice the last three fields (<code>accountId</code>, <code>balance</code>, <code>required</code>). RFC 7807 allows <strong>extension members</strong> — extra properties that carry domain-specific data. Clients must ignore members they do not understand.</p>
<h2>Why <code>type</code> matters more than <code>title</code></h2>
<p>The <code>title</code> is human-friendly text: "Insufficient balance". It is useful in logs and UIs, but it can be localized or reworded.</p>
<p>The <code>type</code> URI is the stable identifier. Client code should branch on <code>type</code>, not on string-matching <code>title</code> or <code>detail</code>:</p>
<pre><code class="language-javascript">if (problem.type.endsWith("/insufficient-balance")) {
  showBalanceWarning(problem.balance, problem.required);
}
</code></pre>
<p>Point <code>type</code> URIs at documentation you control, e.g. <code>https://api.example.com/problems/insufficient-balance</code>. Clients should not depend on dereferencing that URI at runtime.</p>
<h2>Spring Boot makes this straightforward</h2>
<p>Since Spring Framework 6, the <code>org.springframework.http.ProblemDetail</code> class maps directly to RFC 7807. Spring MVC serializes it as <code>application/problem+json</code> when returned from a controller or <code>@RestControllerAdvice</code>.</p>
<p>Enable automatic Problem Details for framework exceptions with one property:</p>
<pre><code class="language-properties">spring.mvc.problemdetails.enabled=true
</code></pre>
<p>For Bean Validation failures, override <code>handleMethodArgumentNotValid</code> on <code>ResponseEntityExceptionHandler</code> so field errors appear as extension members:</p>
<pre><code class="language-java">@RestControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

    @Override
    protected ResponseEntity&lt;Object&gt; handleMethodArgumentNotValid(
            MethodArgumentNotValidException ex, HttpHeaders headers,
            HttpStatusCode status, WebRequest request) {
        ProblemDetail problem = ProblemDetail.forStatusAndDetail(
            HttpStatus.BAD_REQUEST, "One or more fields are invalid.");
        problem.setTitle("Validation failed");
        problem.setType(URI.create(ProblemTypes.VALIDATION_ERROR));
        problem.setProperty("errors", fieldErrors(ex));
        return handleExceptionInternal(ex, problem, headers, status, request);
    }
}
</code></pre>
<p>For business-rule failures, a dedicated <code>@ExceptionHandler</code> is enough:</p>
<pre><code class="language-java">@ExceptionHandler(InsufficientBalanceException.class)
ProblemDetail handleInsufficientBalance(InsufficientBalanceException ex, HttpServletRequest request) {
    ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.FORBIDDEN, ex.getMessage());
    problem.setTitle("Insufficient balance");
    problem.setType(URI.create(ProblemTypes.INSUFFICIENT_BALANCE));
    problem.setInstance(URI.create(request.getRequestURI()));
    problem.setProperty("balance", ex.getBalance());
    problem.setProperty("required", ex.getRequired());
    return problem;
}
</code></pre>
<p>No custom DTO, no manual <code>ObjectMapper</code> wiring — Spring handles content negotiation and serialization. See <a href="https://github.com/mnafshin/RFC_7807/blob/main/src/main/java/info/mnafshin/problem_detail_demo/web/GlobalExceptionHandler.java"><code>GlobalExceptionHandler.java</code></a> and <a href="https://github.com/mnafshin/RFC_7807/blob/main/src/main/resources/application.properties"><code>application.properties</code></a> in the repo.</p>
<h2>OpenAPI as the single source of truth</h2>
<p>In most companies, OpenAPI is not an afterthought — it <strong>is</strong> the contract. Product, backend, frontend, mobile, and partner teams all work from the same spec. Client SDKs, server stubs, and mock servers are <strong>generated</strong> from it. Problem Details must be modeled correctly in that spec, or every generated client will handle errors wrong.</p>
<p>This is a different mindset from "write code first, scan annotations later." The workflow looks like this:</p>
<pre><code>openapi.yaml  →  generate server interface + DTOs + client SDKs
       ↓
implement controller + exception handler
       ↓
integration tests verify runtime matches the spec
</code></pre>
<p>The spec comes first. Code follows.</p>
<h3>Model RFC 7807 problems in the spec</h3>
<p>Define a reusable base schema for the standard RFC 7807 fields, then extend it per error type with <code>allOf</code>:</p>
<pre><code class="language-yaml">components:
  schemas:
    ProblemDetailBase:
      type: object
      required: [type, title, status]
      properties:
        type:     { type: string, format: uri }
        title:    { type: string }
        status:   { type: integer, format: int32 }
        detail:   { type: string }
        instance: { type: string, format: uri }

    AccountNotFoundProblem:
      allOf:
        - $ref: '#/components/schemas/ProblemDetailBase'
        - type: object
          properties:
            accountId: { type: string }

    InsufficientBalanceProblem:
      allOf:
        - $ref: '#/components/schemas/ProblemDetailBase'
        - type: object
          properties:
            accountId: { type: string }
            balance:   { type: integer }
            required:  { type: integer }
</code></pre>
<p>Then reference each problem schema on the endpoint with the correct media type:</p>
<pre><code class="language-yaml">/accounts/{id}:
  get:
    responses:
      '200':
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/Account'
      '404':
        description: Account not found
        content:
          application/problem+json:
            schema:
              $ref: '#/components/schemas/AccountNotFoundProblem'
</code></pre>
<p>Three rules matter for codegen:</p>
<ol>
<li><p><strong>Use <code>application/problem+json</code></strong>, not <code>application/json</code>, on every error response. Client generators bind responses by media type. If you omit it or default to <code>application/json</code>, generated clients will deserialize errors into the wrong type.</p>
</li>
<li><p><strong>One schema per problem type</strong>, not one generic "Error" object. A 404 account-not-found problem carries different extension fields than a 403 insufficient-balance problem. Generated clients need distinct types to branch on.</p>
</li>
<li><p><strong>Put extension fields at the top level</strong> in the schema (via <code>allOf</code>), not nested under a <code>properties</code> bag. That matches what RFC 7807 specifies and what Spring's <code>ProblemDetail</code> actually serializes.</p>
</li>
</ol>
<p>This repo's SSOT lives at <a href="https://github.com/mnafshin/RFC_7807/blob/main/openapi/openapi.yaml"><code>openapi/openapi.yaml</code></a>.</p>
<h3>Generate server code from the spec</h3>
<p>Use the <a href="https://openapi-generator.tech/">OpenAPI Generator</a> Gradle plugin to produce a Spring controller interface and request/response models. The full <a href="https://github.com/mnafshin/RFC_7807/blob/main/build.gradle"><code>build.gradle</code></a> is in the repo; the essentials:</p>
<pre><code class="language-gradle">plugins {
    id 'org.openapi.generator' version '7.13.0'
}

openApiGenerate {
    generatorName = 'spring'
    inputSpec = "$rootDir/openapi/openapi.yaml"
    outputDir = "$buildDir/generated/openapi"
    apiPackage = 'info.mnafshin.problem_detail_demo.api'
    modelPackage = 'info.mnafshin.problem_detail_demo.api.model'
    configOptions = [
        interfaceOnly       : 'true',
        useSpringBoot3      : 'true',
        useBeanValidation   : 'true',
        skipDefaultInterface: 'true',
    ]
}

sourceSets.main.java.srcDirs += "$buildDir/generated/openapi/src/main/java"
compileJava.dependsOn tasks.openApiGenerate
</code></pre>
<p>This generates an <code>AccountsApi</code> interface with method signatures, paths, and validation annotations already wired. <a href="https://github.com/mnafshin/RFC_7807/blob/main/src/main/java/info/mnafshin/problem_detail_demo/account/AccountController.java"><code>AccountController</code></a> implements it:</p>
<pre><code class="language-java">@RestController
public class AccountController implements AccountsApi {

    @Override
    public ResponseEntity&lt;Account&gt; getAccount(String id) {
        return ResponseEntity.ok(accountService.findById(id));
    }
}
</code></pre>
<p>The generated models (<code>Account</code>, <code>WithdrawRequest</code>, <code>AccountNotFoundProblem</code>, …) are the DTOs your API exposes. You do not hand-write parallel Java classes — the spec is the only place those shapes are defined.</p>
<p>Run <code>./gradlew openApiGenerate</code> after every spec change. Commit the YAML; let CI regenerate Java on each build.</p>
<h3>Generate client SDKs from the same spec</h3>
<p>The same <code>openapi.yaml</code> produces consumer code. Generate a Java client for a backend service, or TypeScript for a frontend:</p>
<pre><code class="language-gradle">tasks.register('openApiGenerateClient', org.openapitools.generator.gradle.plugin.tasks.GenerateTask) {
    generatorName = 'java'
    inputSpec = "$rootDir/openapi/openapi.yaml"
    outputDir = "$buildDir/generated/client"
    configOptions = [
        library: 'native',
        apiPackage: 'com.example.client.api',
        modelPackage: 'com.example.client.model',
    ]
}
</code></pre>
<p>The generated client knows that a <code>404</code> on <code>GET /accounts/{id}</code> deserializes to <code>AccountNotFoundProblem</code>, not a generic exception. It can read <code>problem.getAccountId()</code> because the spec defined that extension field.</p>
<p>That is the payoff of modeling Problem Details in OpenAPI: <strong>errors become typed, branchable objects in every language</strong> — not opaque JSON maps.</p>
<h3>Wire runtime errors to match the spec</h3>
<p>Code generation covers happy-path DTOs and the API surface. Errors still flow through your exception handler at runtime, returning Spring's <code>ProblemDetail</code>:</p>
<pre><code class="language-java">problem.setType(URI.create(ProblemTypes.INSUFFICIENT_BALANCE));
problem.setProperty("balance", ex.getBalance());
problem.setProperty("required", ex.getRequired());
</code></pre>
<p>The JSON Spring emits must match the schema in <code>openapi.yaml</code>. The generated <code>InsufficientBalanceProblem</code> model describes the same shape — use it in client code; use <code>ProblemDetail</code> on the server. Both come from one spec.</p>
<p>Keep them aligned with two test layers:</p>
<ul>
<li><strong>Runtime tests</strong> — assert the live response body and <code>Content-Type: application/problem+json</code></li>
<li><strong>Spec tests</strong> — assert <code>openapi.yaml</code> declares every error response; run <code>openApiValidate</code> in CI</li>
</ul>
<pre><code class="language-bash">./gradlew openApiValidate   # spec is well-formed
./gradlew test              # runtime matches declared errors
</code></pre>
<h3>Browse the contract in Swagger UI</h3>
<p>Swagger UI should render the SSOT file, not a separately maintained copy. Serve the same YAML and point springdoc at it:</p>
<pre><code class="language-properties">springdoc.api-docs.enabled=false
springdoc.swagger-ui.url=/openapi/openapi.yaml
</code></pre>
<p>Open <a href="http://localhost:8080/swagger-ui.html">http://localhost:8080/swagger-ui.html</a> after <code>./gradlew bootRun</code> — what you see is exactly what clients and codegen tools consume.</p>
<h3>Code-first vs contract-first</h3>
<table>
<thead>
<tr>
<th>Approach</th>
<th>How the spec is produced</th>
<th>Problem with Problem Details</th>
</tr>
</thead>
<tbody><tr>
<td><strong>Code-first</strong> (springdoc scans annotations)</td>
<td>Generated from <code>@ApiResponse</code> on controllers</td>
<td>Easy to forget error responses; extension fields need duplicate schema classes</td>
</tr>
<tr>
<td><strong>Contract-first</strong> (OpenAPI SSOT)</td>
<td>Authored in YAML; code is generated</td>
<td>Errors are first-class in the spec from day one; clients and server share one truth</td>
</tr>
</tbody></table>
<p>If your organization already treats OpenAPI as SSOT — and most do at scale — model Problem Details in the YAML before writing Java. Do not bolt them on with annotations after the fact.</p>
<h2>Try the demo</h2>
<p>The <a href="https://github.com/mnafshin/RFC_7807">RFC_7807 repository</a> includes a small Spring Boot app — a credits account service with three error scenarios:</p>
<table>
<thead>
<tr>
<th>Scenario</th>
<th>Status</th>
<th><code>type</code> suffix</th>
</tr>
</thead>
<tbody><tr>
<td>Account not found</td>
<td>404</td>
<td><code>/account-not-found</code></td>
</tr>
<tr>
<td>Insufficient balance</td>
<td>403</td>
<td><code>/insufficient-balance</code></td>
</tr>
<tr>
<td>Invalid withdraw amount</td>
<td>400</td>
<td><code>/validation-error</code></td>
</tr>
</tbody></table>
<p>Seeded accounts: <code>123</code> (Ada Lovelace, 30 credits) and <code>456</code> (Grace Hopper, 500 credits).</p>
<pre><code class="language-bash">git clone https://github.com/mnafshin/RFC_7807.git
cd RFC_7807
./gradlew bootRun
</code></pre>
<p>Trigger an insufficient-balance problem:</p>
<pre><code class="language-bash">curl -s -X POST http://localhost:8080/accounts/123/withdraw \
  -H 'Content-Type: application/json' \
  -d '{"amount": 50}' | jq
</code></pre>
<p>Then open Swagger UI and compare the live 403 response to the <code>InsufficientBalanceProblem</code> schema in the spec.</p>
<p>Regenerate server stubs after any spec change:</p>
<pre><code class="language-bash">./gradlew openApiGenerate
</code></pre>
<h2>Prove it with integration tests</h2>
<p>Three layers to lock in CI:</p>
<table>
<thead>
<tr>
<th>Test</th>
<th>What it guards</th>
</tr>
</thead>
<tbody><tr>
<td><code>openApiValidate</code></td>
<td>The SSOT YAML (<a href="https://github.com/mnafshin/RFC_7807/blob/main/openapi/openapi.yaml"><code>openapi/openapi.yaml</code></a>) is well-formed</td>
</tr>
<tr>
<td><a href="https://github.com/mnafshin/RFC_7807/blob/main/src/test/java/info/mnafshin/problem_detail_demo/openapi/OpenApiIntegrationTest.java"><code>OpenApiIntegrationTest</code></a></td>
<td>The spec declares <code>application/problem+json</code> errors</td>
</tr>
<tr>
<td><a href="https://github.com/mnafshin/RFC_7807/blob/main/src/test/java/info/mnafshin/problem_detail_demo/account/AccountControllerIntegrationTest.java"><code>AccountControllerIntegrationTest</code></a></td>
<td>Runtime responses match those declared shapes</td>
</tr>
</tbody></table>
<p><code>AccountControllerIntegrationTest</code> asserts the live error body:</p>
<pre><code class="language-java">mockMvc.perform(get("/accounts/999"))
    .andExpect(status().isNotFound())
    .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_PROBLEM_JSON))
    .andExpect(jsonPath("$.type").value(
        "https://problem-detail-demo.mnafshin.info/problems/account-not-found"))
    .andExpect(jsonPath("$.accountId").value("999"));
</code></pre>
<p><code>OpenApiIntegrationTest</code> asserts the committed spec — not a separately generated copy — declares those same errors.</p>
<pre><code class="language-bash">./gradlew test          # runtime + spec contract
./gradlew openApiValidate   # YAML validity
</code></pre>
<p>Locking both contracts in CI catches breaking changes before any client does.</p>
<h2>Design tips from the spec</h2>
<p><strong>Keep <code>title</code> stable, vary <code>detail</code>.</strong> "Insufficient balance" is the class; "Account 123 has 30 credits but this operation costs 50" is the instance.</p>
<p><strong>Align body <code>status</code> with the HTTP status.</strong> They should always match. The body field is advisory for offline log analysis, not a second authority.</p>
<p><strong>Use extensions for machine-readable extras.</strong> Put anything a client might act on — field names, retry-after hints, error codes — in extension properties rather than embedding them in free-text <code>detail</code>.</p>
<p><strong>Do not replace HTTP semantics.</strong> A <code>404</code> is still a <code>404</code>. Problem Details add context; they do not turn every failure into <code>200 OK</code> with an error payload.</p>
<p><strong>Document every error in the SSOT before implementing it.</strong> If it is not in <code>openapi.yaml</code>, do not generate client code for it — and do not expect consumers to handle it.</p>
<h2>When Problem Details are worth it</h2>
<p>Adopt them when:</p>
<ul>
<li>Multiple clients or teams consume your API</li>
<li>You publish OpenAPI docs and generate clients from them</li>
<li>You operate several microservices and want a shared error contract</li>
</ul>
<p>Skip them when you own the only client and will never expose the API externally — though even then, a consistent internal format pays off in debugging time.</p>
<h2>Further reading</h2>
<ul>
<li><a href="https://www.rfc-editor.org/rfc/rfc7807.html">RFC 7807</a> — original specification</li>
<li><a href="https://www.rfc-editor.org/rfc/rfc9457.html">RFC 9457</a> — current standard</li>
<li><a href="https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/http/ProblemDetail.html">Spring Framework <code>ProblemDetail</code> Javadoc</a></li>
<li><a href="https://openapi-generator.tech/">OpenAPI Generator</a> — generate server stubs and client SDKs from the spec</li>
<li><a href="https://github.com/mnafshin/RFC_7807">RFC_7807 on GitHub</a> — companion code and <a href="https://github.com/mnafshin/RFC_7807/blob/main/README.md">README</a></li>
</ul>
<hr />
<p><em>Full source: <a href="https://github.com/mnafshin/RFC_7807">github.com/mnafshin/RFC_7807</a></em></p>
]]></content:encoded></item><item><title><![CDATA[Idempotency Patterns — Create Orders Exactly Once (With Retries)]]></title><description><![CDATA[Git Repo: Retries are a fact of life in distributed systems. A mobile client times out, a load balancer gives up, a service restarts — and the same request…]]></description><link>https://springuniverse.hashnode.dev/idempotency-patterns-create-orders-exactly-once-with-retries</link><guid isPermaLink="true">https://springuniverse.hashnode.dev/idempotency-patterns-create-orders-exactly-once-with-retries</guid><dc:creator><![CDATA[Afshin Amini]]></dc:creator><pubDate>Sat, 09 May 2026 15:19:34 GMT</pubDate><content:encoded><![CDATA[<p>Git Repo: <a href="https://github.com/mnafshin/idempotency">https://github.com/mnafshin/idempotency</a></p>
<h2>Why This Matters</h2>
<p>Retries are a fact of life in distributed systems. A mobile client times out, a load balancer gives up, a service restarts — and the same request arrives twice. Without idempotency, that can mean duplicate orders and duplicate charges.</p>
<p>This repository walks you through <strong>three runnable, progressively richer implementations</strong> so you can teach the pattern, validate it in tests, and eventually ship it in production:</p>
<table>
<thead>
<tr>
<th>Module</th>
<th>Teaches</th>
<th>Audience</th>
</tr>
</thead>
<tbody><tr>
<td><code>idempotency-easy</code> (port 8081)</td>
<td>The core concept — dedup by key</td>
<td>New to idempotency</td>
</tr>
<tr>
<td><code>idempotency-mature</code> (port 8082)</td>
<td>Multi-tenant + payload consistency check</td>
<td>Building multi-tenant APIs</td>
</tr>
<tr>
<td><code>idempotency-production-redis</code> (port 8083)</td>
<td>Filter-based cross-cutting concern + pluggable store (in-memory / Redis)</td>
<td>Production services</td>
</tr>
</tbody></table>
<hr />
<h2>The Idempotency Contract</h2>
<p>A client picks a <strong>random, unique <code>Idempotency-Key</code></strong> per logical operation and sends it as a header.</p>
<pre><code>POST /api/orders
Idempotency-Key: 550e8400-e29b-41d4-a716-446655440000
X-Tenant-ID: 2b8de313-9c3c-4a15-a9b8-0cd1e34be3da
</code></pre>
<p>Rules:</p>
<ul>
<li><strong>First call</strong> → business logic runs, response is <code>201 Created</code>.</li>
<li><strong>Retry with the same key + same payload</strong> → original response is replayed, <code>200 OK</code>, <code>Idempotent-Replayed: true</code> header set. No business logic runs again.</li>
<li><strong>Retry with the same key + different payload</strong> → <code>409 Conflict</code>. Clients can't silently change the intent of an in-flight operation.</li>
<li><strong>Different key</strong> → treated as a new, independent operation.</li>
</ul>
<hr />
<h2>Level 1 — Easy Mode (Teaching)</h2>
<p><strong>Module:</strong> <code>idempotency-easy</code><br /><strong>Goal:</strong> explain idempotency in the fewest moving parts.</p>
<h3>What it does</h3>
<pre><code>POST /api/orders
Idempotency-Key: order-abc
</code></pre>
<ul>
<li>First request → new order, <code>201 Created</code>.</li>
<li>Same key → same order returned, <code>200 OK</code>.</li>
<li>No tenant scope, no payload check — just key dedup.</li>
</ul>
<h3>How it works</h3>
<p><code>EasyOrderService</code> holds a <code>ConcurrentHashMap&lt;String, Order&gt;</code>. On each request it calls <code>putIfAbsent</code>:</p>
<pre><code class="language-java">Order existing = orders.putIfAbsent(idempotencyKey, newOrder);
boolean replayed = existing != null;
return new OrderResult(replayed ? existing : newOrder, replayed);
</code></pre>
<p>The controller computes the HTTP status from the result:</p>
<pre><code class="language-java">return ResponseEntity
    .status(result.replayed() ? HttpStatus.OK : HttpStatus.CREATED)
    .body(result.order());
</code></pre>
<h3>Limitations (and why they matter in the blog)</h3>
<ul>
<li>Stored in <code>HashMap</code> → lost on restart, not shared across instances.</li>
<li>No tenant isolation → two tenants using the same key would collide.</li>
<li>No payload check → a client that accidentally changes the request body gets a silent replay of the wrong data.</li>
</ul>
<p>These are exactly the gaps Level 2 closes.</p>
<hr />
<h2>Level 2 — Mature Mode (Multi-Tenant + Payload Safety)</h2>
<p><strong>Module:</strong> <code>idempotency-mature</code><br /><strong>Goal:</strong> production-oriented semantics without external infrastructure.</p>
<h3>Required headers</h3>
<pre><code>X-Tenant-ID: 2b8de313-9c3c-4a15-a9b8-0cd1e34be3da   # UUID
Idempotency-Key: order-abc                             # max 255 chars
</code></pre>
<h3>What changes</h3>
<h4>Tenant-scoped dedup key</h4>
<pre><code class="language-java">String dedupKey = tenantId + ":" + idempotencyKey;
</code></pre>
<p>Two tenants using <code>order-abc</code> get completely separate records.</p>
<h4>Payload fingerprint</h4>
<pre><code class="language-java">String fingerprint = customerId + ":" + amount;
</code></pre>
<p>This is stored alongside the order. On retry, fingerprints are compared before replaying:</p>
<pre><code class="language-java">if (!stored.requestFingerprint().equals(incomingFingerprint)) {
    throw new IdempotencyConflictException(...);
}
</code></pre>
<p><code>409 Conflict</code> is returned when payloads differ — protecting clients from subtle bugs where a retry accidentally sends different data.</p>
<h4>Race-safe <code>putIfAbsent</code></h4>
<p><code>ConcurrentHashMap.compute()</code> ensures only one thread wins the first write, regardless of how many concurrent retries arrive simultaneously.</p>
<h3>Behavior table</h3>
<table>
<thead>
<tr>
<th>Scenario</th>
<th>Response</th>
</tr>
</thead>
<tbody><tr>
<td>First call</td>
<td><code>201 Created</code></td>
</tr>
<tr>
<td>Retry, same tenant + key + payload</td>
<td><code>200 OK</code> (replay)</td>
</tr>
<tr>
<td>Retry, same tenant + key, <strong>different payload</strong></td>
<td><code>409 Conflict</code></td>
</tr>
<tr>
<td>Same key, different tenant</td>
<td>Independent — both succeed</td>
</tr>
</tbody></table>
<hr />
<h2>Level 3 — Production Mode (Filter-Based + Pluggable Store)</h2>
<p><strong>Module:</strong> <code>idempotency-production-redis</code><br /><strong>Goal:</strong> cross-cutting idempotency at the HTTP layer, switchable between in-memory and Redis.</p>
<h3>The key design insight</h3>
<p>In mature mode, the service owns idempotency. In production mode, that responsibility moves to a <strong>servlet filter</strong> (<code>IdempotencyFilter extends OncePerRequestFilter</code>).</p>
<p>Why? Because idempotency is not business logic — it's a protocol guarantee. The service shouldn't care whether the response it created 24 hours ago is being replayed right now. With the filter in place:</p>
<pre><code>IdempotencyFilter → [cache hit?] → replay stored response (service never called)
                  → [cache miss] → acquire lock → ProductionOrderController → ProductionOrderService
                                                 ↓
                                            store response in HttpReplayStore
                                            release lock
</code></pre>
<p><code>ProductionOrderService</code> becomes a <strong>plain order factory</strong>:</p>
<pre><code class="language-java">// No idempotency logic here — the filter ensures this is called exactly once per key
public Order createOrder(String tenantId, String idempotencyKey, CreateOrderRequest request) {
    return new Order(UUID.randomUUID(), UUID.fromString(tenantId),
                     idempotencyKey, request.customerId(), request.amount(),
                     "pending", Instant.now());
}
</code></pre>
<hr />
<h3>IdempotencyFilter — step by step</h3>
<pre><code>┌─────────────────────────────────────────────────────┐
│  IdempotencyFilter.doFilterInternal()               │
│                                                     │
│  1. Skip non-mutating methods (GET, HEAD, OPTIONS)  │
│     or requests with no Idempotency-Key header      │
│  2. Validate X-Tenant-ID (UUID) + Idempotency-Key   │
│     → 400 Bad Request on violation                  │
│  3. SHA-256 fingerprint of raw request body         │
│  4. Look up dedupKey in HttpReplayStore             │
│     ├─ HIT, same fingerprint  → replay 200 OK       │
│     │                            Idempotent-Replayed: true
│     └─ HIT, diff fingerprint  → 409 Conflict        │
│  5. Cache miss → acquireLock (SETNX in Redis)       │
│     └─ lock held by concurrent thread → 409         │
│  6. Run filter chain (controller + service)         │
│  7. Store response in HttpReplayStore + TTL         │
│     ├─ success → release lock                       │
│     └─ store fails → EXTEND lock (don't release)   │
│        (client gets 5xx; lock prevents unsafe retry)│
└─────────────────────────────────────────────────────┘
</code></pre>
<p>Key implementation details:</p>
<p><strong><code>CachedBodyRequestWrapper</code></strong> — the HTTP request body is a stream that can only be read once. This wrapper caches the raw bytes so the filter can compute the SHA-256 fingerprint <em>and</em> Spring can still deserialize the body downstream.</p>
<p><strong><code>ContentCachingResponseWrapper</code></strong> — the response body is captured after the chain runs so the filter can store it in the replay store before releasing the lock.</p>
<p><strong>SETNX lock</strong> (step 5) — Redis <code>SET … NX EX</code> (or in-memory equivalent). If two threads with the same new key arrive simultaneously, exactly one acquires the lock; the other gets a clear <code>409</code> rather than creating a duplicate order.</p>
<p><strong>Lock retention on store failure</strong> (step 7) — if Redis write fails <em>after</em> the order was created, releasing the lock would allow a retry that creates a second order. Instead, the lock TTL is extended to match the idempotency TTL. The client gets a 5xx, and retrying is unsafe until the lock expires.</p>
<p><strong><code>Idempotent-Replayed: true</code> header</strong> — set on every replayed response so clients, load balancers, and observability tools can distinguish replays from fresh creation responses.</p>
<p><strong>Response size guard</strong> — responses exceeding <code>idempotency.store.max-response-bytes</code> (default 10 MB) are replaced with a <code>409</code> marker record. The business action completed; it just can't be replayed verbatim to avoid OOM.</p>
<hr />
<h3>HttpReplayStore — the pluggable store</h3>
<pre><code class="language-java">public interface HttpReplayStore {
    HttpReplayRecord get(String dedupKey);
    boolean putIfAbsent(String dedupKey, HttpReplayRecord record, Duration ttl);
    boolean acquireLock(String lockKey, Duration ttl);
    void releaseLock(String lockKey);
    void extendLockTtl(String lockKey, Duration ttl);

    record HttpReplayRecord(
        int    statusCode,
        String contentType,
        String body,               // UTF-8 string (JSON in practice)
        String requestFingerprint  // SHA-256 of raw request bytes
    ) {}
}
</code></pre>
<p>Two implementations are wired via <code>@ConditionalOnProperty</code>:</p>
<table>
<thead>
<tr>
<th>Implementation</th>
<th><code>idempotency.store.type</code></th>
<th>Notes</th>
</tr>
</thead>
<tbody><tr>
<td><code>InMemoryHttpReplayStore</code></td>
<td><code>in-memory</code> <em>(default)</em></td>
<td><code>ConcurrentHashMap</code> with TTL. No Redis needed.</td>
</tr>
<tr>
<td><code>RedisHttpReplayStore</code></td>
<td><code>redis</code></td>
<td>Jackson JSON in Redis. Human-readable via <code>redis-cli</code>.</td>
</tr>
</tbody></table>
<p>The filter depends only on the interface — swapping stores requires no code changes.</p>
<h4>What a record looks like in <code>redis-cli</code></h4>
<pre><code># Cache entry
GET order:idempotency:2b8de313-...:order-abc
{"status":201,"contentType":"application/json","body":"{\"id\":\"a1b2...\", ...}","requestFingerprint":"e3b0..."}

# In-flight lock (present only while first request is being processed)
EXISTS order:idempotency:lock:2b8de313-...:order-abc

# Scan all cache entries for a tenant
KEYS order:idempotency:2b8de313-...:*

# Scan all in-flight locks across all tenants
KEYS order:idempotency:lock:*
</code></pre>
<p>The <code>:lock:</code> segment sits <strong>before</strong> the tenant ID — so cache entries and locks are separately scannable namespaces.</p>
<hr />
<h3>Switching to Redis</h3>
<p><strong>Step 1 — start Redis:</strong></p>
<pre><code class="language-bash"># from idempotency-production-redis/
docker compose up -d
</code></pre>
<p>This starts <code>redis:7-alpine</code> on the default port <code>6379</code> with a persistent volume.</p>
<p><strong>Step 2 — run with the <code>redis</code> Spring profile:</strong></p>
<pre><code class="language-bash">./gradlew :idempotency-production-redis:bootRun \
  --args='--spring.profiles.active=redis'
</code></pre>
<p><code>application-redis.properties</code> is activated automatically, overriding:</p>
<pre><code class="language-properties">idempotency.store.type=redis
spring.data.redis.host=localhost
spring.data.redis.port=6379
</code></pre>
<p><strong>Inspect live keys:</strong></p>
<pre><code class="language-bash">docker compose exec redis redis-cli
&gt; KEYS order:idempotency:*               # all cache entries
&gt; KEYS order:idempotency:lock:*          # all in-flight locks
&gt; GET  order:idempotency:2b8de313-...:order-abc
&gt; TTL  order:idempotency:2b8de313-...:order-abc
</code></pre>
<hr />
<h2>Tests</h2>
<h3>Production module test coverage</h3>
<table>
<thead>
<tr>
<th>Test class</th>
<th>Store</th>
<th>What it covers</th>
</tr>
</thead>
<tbody><tr>
<td><code>ProductionOrderServiceTest</code></td>
<td>—</td>
<td>Service creates order with correct fields</td>
</tr>
<tr>
<td><code>OrderIdempotencyIntegrationTest</code></td>
<td>In-memory</td>
<td>12 HTTP-level scenarios</td>
</tr>
<tr>
<td><code>OrderIdempotencyRedisIntegrationTest</code></td>
<td>Real Redis (Testcontainers)</td>
<td>Same scenarios against live Redis</td>
</tr>
</tbody></table>
<h3>Integration test scenarios</h3>
<ol>
<li>First call → <code>201 Created</code></li>
<li>Retry same key + payload → <code>200 OK</code>, <code>Idempotent-Replayed: true</code>, identical body</li>
<li>Retry different payload → <code>409 Conflict</code></li>
<li>Different key → independent <code>201 Created</code></li>
<li>Missing <code>Idempotency-Key</code> → filter skips (passes through)</li>
<li>Missing <code>X-Tenant-ID</code> → <code>400 Bad Request</code></li>
<li>Malformed <code>X-Tenant-ID</code> → <code>400 Bad Request</code></li>
<li>Empty <code>Idempotency-Key</code> → <code>400 Bad Request</code></li>
<li>Oversized <code>Idempotency-Key</code> (&gt; 255 chars) → <code>400 Bad Request</code></li>
<li>Same key, different tenants → isolated; both get <code>201</code></li>
<li>GET request → filter skips; no idempotency logic applied</li>
<li><strong>20 concurrent threads, same key</strong> → exactly one order created; all others get <code>409</code> (SETNX lock)</li>
</ol>
<h3>Testcontainers Redis wiring</h3>
<pre><code class="language-java">@Container
static GenericContainer&lt;?&gt; redis =
    new GenericContainer&lt;&gt;(DockerImageName.parse("redis:7-alpine"))
        .withExposedPorts(6379);

@DynamicPropertySource
static void redisProperties(DynamicPropertyRegistry registry) {
    registry.add("spring.data.redis.host", redis::getHost);
    registry.add("spring.data.redis.port", () -&gt; redis.getMappedPort(6379));
}
</code></pre>
<p><code>@DynamicPropertySource</code> injects the container's ephemeral port into the Spring context before it starts — no hardcoded ports, no external infrastructure in CI.</p>
<p>Run only the Redis-backed tests:</p>
<pre><code class="language-bash">./gradlew :idempotency-production-redis:test \
  --tests "*.OrderIdempotencyRedisIntegrationTest"
</code></pre>
<hr />
<h2>Running All Three Modules</h2>
<pre><code class="language-bash">./gradlew :idempotency-easy:bootRun
./gradlew :idempotency-mature:bootRun
./gradlew :idempotency-production-redis:bootRun
</code></pre>
<h3>Easy — port 8081</h3>
<pre><code class="language-bash"># First call
curl -i -X POST http://localhost:8081/api/orders \
  -H 'Content-Type: application/json' \
  -H 'Idempotency-Key: order-123' \
  -d '{"customerId":"25dfc44e-3ed7-4eb4-b412-6a6df8c6d355","amount":99.99}'
# → 201 Created

# Retry — same key, same payload
curl -i -X POST http://localhost:8081/api/orders \
  -H 'Content-Type: application/json' \
  -H 'Idempotency-Key: order-123' \
  -d '{"customerId":"25dfc44e-3ed7-4eb4-b412-6a6df8c6d355","amount":99.99}'
# → 200 OK  (same id, same createdAt)
</code></pre>
<h3>Mature — port 8082</h3>
<pre><code class="language-bash"># First call
curl -i -X POST http://localhost:8082/api/orders \
  -H 'Content-Type: application/json' \
  -H 'X-Tenant-ID: 2b8de313-9c3c-4a15-a9b8-0cd1e34be3da' \
  -H 'Idempotency-Key: order-123' \
  -d '{"customerId":"25dfc44e-3ed7-4eb4-b412-6a6df8c6d355","amount":99.99}'
# → 201 Created

# Payload mismatch
curl -i -X POST http://localhost:8082/api/orders \
  -H 'Content-Type: application/json' \
  -H 'X-Tenant-ID: 2b8de313-9c3c-4a15-a9b8-0cd1e34be3da' \
  -H 'Idempotency-Key: order-123' \
  -d '{"customerId":"25dfc44e-3ed7-4eb4-b412-6a6df8c6d355","amount":999.99}'
# → 409 Conflict
</code></pre>
<h3>Production — port 8083</h3>
<pre><code class="language-bash"># First call
curl -i -X POST http://localhost:8083/api/orders \
  -H 'Content-Type: application/json' \
  -H 'X-Tenant-ID: 2b8de313-9c3c-4a15-a9b8-0cd1e34be3da' \
  -H 'Idempotency-Key: order-123' \
  -d '{"customerId":"25dfc44e-3ed7-4eb4-b412-6a6df8c6d355","amount":99.99}'
# → 201 Created

# Retry — filter replays, service never called:
curl -i -X POST http://localhost:8083/api/orders \
  -H 'Content-Type: application/json' \
  -H 'X-Tenant-ID: 2b8de313-9c3c-4a15-a9b8-0cd1e34be3da' \
  -H 'Idempotency-Key: order-123' \
  -d '{"customerId":"25dfc44e-3ed7-4eb4-b412-6a6df8c6d355","amount":99.99}'
# → 200 OK
# Idempotent-Replayed: true
</code></pre>
<hr />
<h2>Configuration Reference</h2>
<p>All values in <code>idempotency-production-redis/src/main/resources/application.properties</code>:</p>
<table>
<thead>
<tr>
<th>Property</th>
<th>Default</th>
<th>Description</th>
</tr>
</thead>
<tbody><tr>
<td><code>idempotency.store.type</code></td>
<td><code>in-memory</code></td>
<td><code>in-memory</code> or <code>redis</code></td>
</tr>
<tr>
<td><code>idempotency.store.key-prefix</code></td>
<td><code>order:idempotency:</code></td>
<td>Redis key namespace</td>
</tr>
<tr>
<td><code>idempotency.store.ttl</code></td>
<td><code>PT24H</code></td>
<td>How long completed responses are kept</td>
</tr>
<tr>
<td><code>idempotency.store.lock-ttl</code></td>
<td><code>PT30S</code></td>
<td>Max time an in-flight lock is held</td>
</tr>
<tr>
<td><code>idempotency.store.max-response-bytes</code></td>
<td><code>10485760</code> (10 MB)</td>
<td>Oversized responses get a marker instead of being cached</td>
</tr>
</tbody></table>
<hr />
<h2>Pattern Progression (Beyond This Repo)</h2>
<table>
<thead>
<tr>
<th>Level</th>
<th>Approach</th>
<th>Trade-offs</th>
</tr>
</thead>
<tbody><tr>
<td>1</td>
<td><code>ConcurrentHashMap</code></td>
<td>Simple; in-process only</td>
</tr>
<tr>
<td>2</td>
<td>Tenant-scoped map + fingerprint</td>
<td>Multi-tenant; still single-instance</td>
</tr>
<tr>
<td>3 <em>(this repo)</em></td>
<td>Filter + pluggable store (in-memory / Redis)</td>
<td>Horizontally scalable; no DB dependency</td>
</tr>
<tr>
<td>4</td>
<td>Redis + DB unique constraint on <code>(tenant_id, idempotency_key)</code></td>
<td>Durable across Redis restarts</td>
</tr>
<tr>
<td>5</td>
<td>Outbox / event store</td>
<td>Full audit trail; at-least-once delivery</td>
</tr>
</tbody></table>
<p>The filter approach in Level 3 is the right production baseline for most REST APIs: transparent to the service, testable in isolation, and the store can be swapped without touching business logic.</p>
<hr />
<h2>Known Limits (Intentional for Teaching)</h2>
<ul>
<li><strong>No SQL persistence</strong> — Redis data loss means idempotency history is lost. A unique constraint on the orders table is the next step.</li>
<li><strong>No distributed lock</strong> — the Redis lock is best-effort; a Redis failover mid-lock could theoretically allow a duplicate. Redlock or a DB advisory lock eliminates this.</li>
<li><strong>No metrics</strong> — adding Micrometer counters (<code>idempotency.hit</code>, <code>idempotency.miss</code>, <code>idempotency.conflict</code>) is the obvious next production addition.</li>
<li><strong>In-memory store is per-instance</strong> — run two instances without Redis and deduplication breaks across them.</li>
</ul>
<hr />
<h2>Summary</h2>
<p>Idempotency is a <strong>protocol guarantee</strong>, not a business rule. Keeping it in a filter (rather than the service) means:</p>
<ul>
<li>The <strong>service stays a plain factory</strong> — easy to test, easy to reason about.</li>
<li>You can <strong>swap the store</strong> (in-memory → Redis → DB) without touching business logic.</li>
<li><strong>Replay, conflict detection, locking, and the <code>Idempotent-Replayed</code> header</strong> are all in one place.</li>
</ul>
<p>The three-module structure lets you walk a team from "what is idempotency?" all the way to "here's how we'd ship it."</p>
]]></content:encoded></item><item><title><![CDATA[Multi-Tenancy Architecture in Spring Boot
]]></title><description><![CDATA[This guide explains the four most common multi-tenancy approaches, when to use each, and how to set each one up in a Spring Boot + PostgreSQL system. Git…]]></description><link>https://springuniverse.hashnode.dev/multi-tenancy-architecture-in-spring-boot</link><guid isPermaLink="true">https://springuniverse.hashnode.dev/multi-tenancy-architecture-in-spring-boot</guid><dc:creator><![CDATA[Afshin Amini]]></dc:creator><pubDate>Sat, 09 May 2026 11:08:51 GMT</pubDate><content:encoded><![CDATA[<p>This guide explains the four most common multi-tenancy approaches, when to use each, and how to set each one up in a Spring Boot + PostgreSQL system.</p>
<p>Git link: <a href="https://github.com/mnafshin/multi-tenancy">https://github.com/mnafshin/multi-tenancy</a></p>
<h2>Quick Comparison</h2>
<table>
<thead>
<tr>
<th>Approach</th>
<th>Isolation Level</th>
<th>Complexity</th>
<th>Best For</th>
</tr>
</thead>
<tbody><tr>
<td>Shared database, shared schema (<code>tenant_id</code> column)</td>
<td>Logical</td>
<td>Low</td>
<td>Fastest start, many small tenants</td>
</tr>
<tr>
<td>Shared database, schema per tenant</td>
<td>Stronger logical/namespace</td>
<td>Medium</td>
<td>Moderate tenant count with stricter separation</td>
</tr>
<tr>
<td>Database per tenant</td>
<td>Physical</td>
<td>High</td>
<td>Compliance-heavy or premium isolation</td>
</tr>
<tr>
<td>Hybrid (app filter + DB enforcement)</td>
<td>Defense in depth</td>
<td>Medium-High</td>
<td>Teams that want layered protection</td>
</tr>
</tbody></table>
<h2>1) Shared Database, Shared Schema</h2>
<h3>How it works</h3>
<p>All tenants use the same tables. Every tenant-scoped row carries a <code>tenant_id</code>. The application always filters by <code>tenant_id</code>.</p>
<h3>Setup</h3>
<ol>
<li><p>Add <code>tenant_id</code> to tenant-owned tables.</p>
</li>
<li><p>Create composite indexes with <code>tenant_id</code> as the first column.</p>
</li>
<li><p>Resolve current tenant from request context (header/JWT/subdomain).</p>
</li>
<li><p>Enforce tenant filters in repository/service layer.</p>
</li>
<li><p>Add tests that prove tenant A cannot read tenant B data.</p>
</li>
</ol>
<h3>Example schema</h3>
<pre><code class="language-sql">CREATE TABLE orders (
    id UUID PRIMARY KEY,
    tenant_id TEXT NOT NULL,
    customer_id TEXT NOT NULL,
    amount NUMERIC(12,2) NOT NULL,
    status TEXT NOT NULL,
    created_at TIMESTAMP NOT NULL DEFAULT NOW()
);

CREATE INDEX idx_orders_tenant_status ON orders (tenant_id, status);
</code></pre>
<h3>Spring setup pattern</h3>
<pre><code class="language-java">public List&lt;Order&gt; listOrders(String tenantId, String status) {
    return orderRepository.findByTenantIdAndStatus(tenantId, status);
}
</code></pre>
<h3>Notes</h3>
<ul>
<li><p>Easiest to implement and operate.</p>
</li>
<li><p>Biggest risk is developer mistakes (missing tenant filter in one query).</p>
</li>
</ul>
<hr />
<h2>2) Shared Database, Schema per Tenant</h2>
<h3>How it works</h3>
<p>All tenants share one PostgreSQL instance, but each tenant has its own schema (<code>tenant_a.orders</code>, <code>tenant_b.orders</code>, ...).</p>
<h3>Setup</h3>
<ol>
<li><p>Provision one schema per tenant.</p>
</li>
<li><p>Keep schema structure identical across tenants.</p>
</li>
<li><p>Switch schema per request using <code>SET search_path</code>.</p>
</li>
<li><p>Run migrations for each tenant schema.</p>
</li>
<li><p>Add tests that verify data in schema A is invisible from schema B.</p>
</li>
</ol>
<h3>Example provisioning</h3>
<pre><code class="language-sql">CREATE SCHEMA tenant_a;
CREATE SCHEMA tenant_b;

CREATE TABLE tenant_a.orders (
    id UUID PRIMARY KEY,
    customer_id TEXT NOT NULL,
    amount NUMERIC(12,2) NOT NULL
);

CREATE TABLE tenant_b.orders (
    id UUID PRIMARY KEY,
    customer_id TEXT NOT NULL,
    amount NUMERIC(12,2) NOT NULL
);
</code></pre>
<h3>Spring setup pattern</h3>
<pre><code class="language-java">// Pseudocode before each request/transaction
jdbcTemplate.execute("SET search_path TO " + tenantSchema + ", public");
</code></pre>
<h3>Notes</h3>
<ul>
<li><p>Better isolation than shared-schema.</p>
</li>
<li><p>Migrations and onboarding/offboarding tenants are more operationally complex.</p>
</li>
</ul>
<hr />
<h2>3) Database per Tenant</h2>
<h3>How it works</h3>
<p>Each tenant gets an independent database (or server). Application routes connections by tenant id.</p>
<h3>Setup</h3>
<ol>
<li><p>Create database per tenant (<code>orders_tenant_a</code>, <code>orders_tenant_b</code>, ...).</p>
</li>
<li><p>Maintain a tenant registry mapping <code>tenant_id -&gt; JDBC URL/credentials</code>.</p>
</li>
<li><p>Route at <code>DataSource</code> layer (e.g., <code>AbstractRoutingDataSource</code>).</p>
</li>
<li><p>Apply migrations per tenant database.</p>
</li>
<li><p>Add tests proving each database contains only its own data.</p>
</li>
</ol>
<h3>Spring setup pattern</h3>
<pre><code class="language-java">public class TenantRoutingDataSource extends AbstractRoutingDataSource {
    @Override
    protected Object determineCurrentLookupKey() {
        return TenantContext.getTenantId();
    }
}
</code></pre>
<h3>Notes</h3>
<ul>
<li><p>Strongest isolation and easiest compliance narrative.</p>
</li>
<li><p>Highest cost and operational overhead (pooling, backups, migrations per DB).</p>
</li>
</ul>
<hr />
<h2>4) Hybrid: Application Filtering + Database Enforcement</h2>
<h3>How it works</h3>
<p>Use app-level tenant checks and repository filtering, plus DB-level enforcement (for example PostgreSQL RLS). This reduces the blast radius of one-layer mistakes.</p>
<h3>Setup</h3>
<ol>
<li><p>Keep explicit <code>tenant_id</code> filtering in app queries.</p>
</li>
<li><p>Add RLS policy in PostgreSQL.</p>
</li>
<li><p>Set tenant context in DB session (<code>SET app.tenant_id = ...</code>).</p>
</li>
<li><p>Restrict direct table access to non-admin roles used by app.</p>
</li>
<li><p>Test both normal flow and bypass attempts.</p>
</li>
</ol>
<h3>Example PostgreSQL RLS</h3>
<pre><code class="language-sql">ALTER TABLE orders ENABLE ROW LEVEL SECURITY;

CREATE POLICY tenant_isolation_orders ON orders
USING (tenant_id = current_setting('app.tenant_id')::text);
</code></pre>
<h3>Notes</h3>
<ul>
<li><p>Most secure in practice for shared infrastructure.</p>
</li>
<li><p>Requires disciplined session handling and more observability.</p>
</li>
</ul>
<hr />
<h2>Choosing an Approach</h2>
<ul>
<li><p>Start with <strong>shared schema</strong> if you need speed and have strong test/lint guardrails.</p>
</li>
<li><p>Move to <strong>schema per tenant</strong> when you need stronger isolation without full DB sprawl.</p>
</li>
<li><p>Use <strong>database per tenant</strong> for strict compliance, noisy-neighbor protection, or premium tenants.</p>
</li>
<li><p>Use <strong>hybrid</strong> when you want defense-in-depth while keeping shared infrastructure economics.</p>
</li>
</ul>
<h2>Integration Test Coverage in This Repository</h2>
<p>The following integration tests validate isolation behavior for each model:</p>
<ul>
<li><p><code>SharedSchemaIsolationIntegrationTest</code></p>
</li>
<li><p><code>SchemaPerTenantIsolationIntegrationTest</code></p>
</li>
<li><p><code>DatabasePerTenantIsolationIntegrationTest</code></p>
</li>
<li><p><code>HybridIsolationIntegrationTest</code></p>
</li>
</ul>
<p>They run against PostgreSQL via Testcontainers and can be executed with:</p>
<pre><code class="language-bash">./gradlew test
</code></pre>
]]></content:encoded></item><item><title><![CDATA[Java Synchronization Mechanisms: A Comprehensive Comparison]]></title><description><![CDATA[Explore Java synchronization mechanisms such as intrinsic locks, ReentrantLock, and ReadWriteLock to ensure thread safety and prevent data races]]></description><link>https://springuniverse.hashnode.dev/java-synchronization-mechanisms-a-comprehensive-comparison</link><guid isPermaLink="true">https://springuniverse.hashnode.dev/java-synchronization-mechanisms-a-comprehensive-comparison</guid><category><![CDATA[Java]]></category><category><![CDATA[lock]]></category><dc:creator><![CDATA[Afshin Amini]]></dc:creator><pubDate>Mon, 16 Feb 2026 01:15:54 GMT</pubDate><content:encoded><![CDATA[<h1 id="heading-java-synchronization-mechanisms-a-comprehensive-comparison">Java Synchronization Mechanisms: A Comprehensive Comparison</h1>
<h2 id="heading-introduction">Introduction</h2>
<p>Concurrent programming in Java requires careful management of shared resources. The Java platform provides multiple synchronization mechanisms to prevent data races and ensure thread safety. This blog post explores the nuances of intrinsic locks, <code>ReentrantLock</code>, <code>ReadWriteLock</code>, <code>Semaphore</code>, and other synchronization primitives, helping you choose the right tool for your specific use case.</p>
<hr />
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><a class="post-section-overview" href="#intrinsic-locks">Intrinsic Locks (synchronized)</a></li>
<li><a class="post-section-overview" href="#reentrantlock">ReentrantLock</a></li>
<li><a class="post-section-overview" href="#readwritelock">ReadWriteLock</a></li>
<li><a class="post-section-overview" href="#reentrantreadwritelock">ReentrantReadWriteLock</a></li>
<li><a class="post-section-overview" href="#semaphore">Semaphore</a></li>
<li><a class="post-section-overview" href="#stampedlock">StampedLock</a></li>
<li><a class="post-section-overview" href="#countdownlatch">CountDownLatch</a></li>
<li><a class="post-section-overview" href="#cyclicbarrier">CyclicBarrier</a></li>
<li><a class="post-section-overview" href="#phaser">Phaser</a></li>
<li><a class="post-section-overview" href="#comparison-table">Comparison Table</a></li>
<li><a class="post-section-overview" href="#best-practices">Best Practices</a></li>
</ol>
<hr />
<h2 id="heading-intrinsic-locks-intrinsic-locks">Intrinsic Locks {#intrinsic-locks}</h2>
<h3 id="heading-overview">Overview</h3>
<p>Intrinsic locks (also called monitor locks) are the synchronization mechanism built into the Java language itself. Every object in Java has an associated lock that is automatically managed by the JVM.</p>
<h3 id="heading-usage">Usage</h3>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Counter</span> </span>{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> count = <span class="hljs-number">0</span>;

    <span class="hljs-comment">// Synchronize on the instance</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">synchronized</span> <span class="hljs-keyword">void</span> <span class="hljs-title">increment</span><span class="hljs-params">()</span> </span>{
        count++;
    }

    <span class="hljs-comment">// Synchronize on a specific object</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">incrementSafe</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">synchronized</span>(<span class="hljs-keyword">this</span>) {
            count++;
        }
    }
}
</code></pre>
<h3 id="heading-characteristics">Characteristics</h3>
<ul>
<li><strong>Automatic Release</strong>: Locks are automatically released when exiting a synchronized block</li>
<li><strong>Reentrancy</strong>: The same thread can acquire the same lock multiple times</li>
<li><strong>No Timeout</strong>: Cannot timeout waiting for a lock</li>
<li><strong>Simple</strong>: Easy to use and understand</li>
<li><strong>JVM Optimizations</strong>: Subject to optimization (biased locking, lock coarsening)</li>
</ul>
<h3 id="heading-advantages">Advantages</h3>
<p>✅ Simple and straightforward syntax<br />✅ Automatically released (no risk of forgetting to unlock)<br />✅ Reentrant by default<br />✅ Efficient for uncontended locks  </p>
<h3 id="heading-disadvantages">Disadvantages</h3>
<p>❌ Cannot check if lock is available without attempting to acquire it<br />❌ No timeout support<br />❌ Must use nested synchronized blocks for multiple locks (deadlock risk)<br />❌ Less flexible than explicit locks  </p>
<h3 id="heading-example">Example</h3>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">BankAccount</span> </span>{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">double</span> balance = <span class="hljs-number">0</span>;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">synchronized</span> <span class="hljs-keyword">void</span> <span class="hljs-title">deposit</span><span class="hljs-params">(<span class="hljs-keyword">double</span> amount)</span> </span>{
        balance += amount;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">synchronized</span> <span class="hljs-keyword">void</span> <span class="hljs-title">withdraw</span><span class="hljs-params">(<span class="hljs-keyword">double</span> amount)</span> </span>{
        balance -= amount;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">synchronized</span> <span class="hljs-keyword">double</span> <span class="hljs-title">getBalance</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> balance;
    }
}
</code></pre>
<hr />
<h2 id="heading-reentrantlock-reentrantlock">ReentrantLock {#reentrantlock}</h2>
<h3 id="heading-overview-1">Overview</h3>
<p><code>ReentrantLock</code> is an explicit implementation of the <code>Lock</code> interface that provides similar functionality to intrinsic locks but with additional features and flexibility.</p>
<h3 id="heading-usage-1">Usage</h3>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.concurrent.locks.ReentrantLock;
<span class="hljs-keyword">import</span> java.util.concurrent.locks.Lock;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Counter</span> </span>{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> count = <span class="hljs-number">0</span>;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> Lock lock = <span class="hljs-keyword">new</span> ReentrantLock();

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">increment</span><span class="hljs-params">()</span> </span>{
        lock.lock();
        <span class="hljs-keyword">try</span> {
            count++;
        } <span class="hljs-keyword">finally</span> {
            lock.unlock();
        }
    }
}
</code></pre>
<h3 id="heading-characteristics-1">Characteristics</h3>
<ul>
<li><strong>Explicit Control</strong>: Manual lock and unlock</li>
<li><strong>Reentrancy</strong>: Same thread can acquire multiple times</li>
<li><strong>Fairness</strong>: Optional fair queuing policy (FIFO)</li>
<li><strong>Timeout Support</strong>: Can timeout waiting for lock</li>
<li><strong>Interruptible</strong>: Can be interrupted while waiting</li>
<li><strong>Try Lock</strong>: Can attempt non-blocking lock acquisition</li>
</ul>
<h3 id="heading-advantages-1">Advantages</h3>
<p>✅ Supports timeout with <code>tryLock(long, TimeUnit)</code><br />✅ Interruptible via <code>lockInterruptibly()</code><br />✅ Can check lock status with <code>tryLock()</code><br />✅ Fair scheduling option available<br />✅ Works with Conditions for advanced synchronization  </p>
<h3 id="heading-disadvantages-1">Disadvantages</h3>
<p>❌ Manual unlock required (easy to forget)<br />❌ More verbose than <code>synchronized</code><br />❌ Slightly higher overhead than intrinsic locks  </p>
<h3 id="heading-example-1">Example</h3>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.concurrent.TimeUnit;
<span class="hljs-keyword">import</span> java.util.concurrent.locks.ReentrantLock;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TimedLockExample</span> </span>{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> ReentrantLock lock = <span class="hljs-keyword">new</span> ReentrantLock();
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> value = <span class="hljs-number">0</span>;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">updateValue</span><span class="hljs-params">(<span class="hljs-keyword">int</span> newValue)</span> <span class="hljs-keyword">throws</span> InterruptedException </span>{
        <span class="hljs-keyword">if</span> (lock.tryLock(<span class="hljs-number">5</span>, TimeUnit.SECONDS)) {
            <span class="hljs-keyword">try</span> {
                value = newValue;
                System.out.println(<span class="hljs-string">"Value updated to: "</span> + newValue);
            } <span class="hljs-keyword">finally</span> {
                lock.unlock();
            }
        } <span class="hljs-keyword">else</span> {
            System.out.println(<span class="hljs-string">"Could not acquire lock within timeout"</span>);
        }
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">interruptibleUpdate</span><span class="hljs-params">(<span class="hljs-keyword">int</span> newValue)</span> <span class="hljs-keyword">throws</span> InterruptedException </span>{
        lock.lockInterruptibly();
        <span class="hljs-keyword">try</span> {
            value = newValue;
        } <span class="hljs-keyword">finally</span> {
            lock.unlock();
        }
    }
}
</code></pre>
<hr />
<h2 id="heading-readwritelock-readwritelock">ReadWriteLock {#readwritelock}</h2>
<h3 id="heading-overview-2">Overview</h3>
<p><code>ReadWriteLock</code> maintains a pair of locks: one for read access and one for write access. Multiple threads can hold the read lock simultaneously, but only one thread can hold the write lock.</p>
<h3 id="heading-characteristics-2">Characteristics</h3>
<ul>
<li><strong>Concurrent Reads</strong>: Multiple threads can read simultaneously</li>
<li><strong>Exclusive Writes</strong>: Only one thread can write, and no reads happen during writes</li>
<li><strong>Improved Throughput</strong>: Better performance when reads greatly outnumber writes</li>
<li><strong>Read-Write Lock Semantics</strong>: Readers don't block each other</li>
</ul>
<h3 id="heading-usage-2">Usage</h3>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.concurrent.locks.ReadWriteLock;
<span class="hljs-keyword">import</span> java.util.concurrent.locks.ReentrantReadWriteLock;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DataCache</span> </span>{
    <span class="hljs-keyword">private</span> String data = <span class="hljs-string">""</span>;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> ReadWriteLock rwLock = <span class="hljs-keyword">new</span> ReentrantReadWriteLock();

    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getData</span><span class="hljs-params">()</span> </span>{
        rwLock.readLock().lock();
        <span class="hljs-keyword">try</span> {
            <span class="hljs-keyword">return</span> data;
        } <span class="hljs-keyword">finally</span> {
            rwLock.readLock().unlock();
        }
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setData</span><span class="hljs-params">(String newData)</span> </span>{
        rwLock.writeLock().lock();
        <span class="hljs-keyword">try</span> {
            data = newData;
        } <span class="hljs-keyword">finally</span> {
            rwLock.writeLock().unlock();
        }
    }
}
</code></pre>
<h3 id="heading-advantages-2">Advantages</h3>
<p>✅ Excellent for read-heavy workloads<br />✅ Multiple concurrent readers<br />✅ Exclusive write access<br />✅ Prevents writer starvation  </p>
<h3 id="heading-disadvantages-2">Disadvantages</h3>
<p>❌ More overhead than simple locks<br />❌ Not beneficial when reads and writes are balanced<br />❌ More complex to understand and use  </p>
<hr />
<h2 id="heading-reentrantreadwritelock-reentrantreadwritelock">ReentrantReadWriteLock {#reentrantreadwritelock}</h2>
<h3 id="heading-overview-3">Overview</h3>
<p><code>ReentrantReadWriteLock</code> is the standard implementation of <code>ReadWriteLock</code> in Java. It provides reentrancy for both read and write locks with optional fairness.</p>
<h3 id="heading-example-2">Example</h3>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.concurrent.locks.ReentrantReadWriteLock;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CachedData</span> </span>{
    <span class="hljs-keyword">private</span> String value = <span class="hljs-string">""</span>;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> ReentrantReadWriteLock lock = <span class="hljs-keyword">new</span> ReentrantReadWriteLock();

    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getValue</span><span class="hljs-params">()</span> </span>{
        lock.readLock().lock();
        <span class="hljs-keyword">try</span> {
            <span class="hljs-keyword">return</span> value;
        } <span class="hljs-keyword">finally</span> {
            lock.readLock().unlock();
        }
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setValue</span><span class="hljs-params">(String newValue)</span> </span>{
        lock.writeLock().lock();
        <span class="hljs-keyword">try</span> {
            value = newValue;
        } <span class="hljs-keyword">finally</span> {
            lock.writeLock().unlock();
        }
    }

    <span class="hljs-comment">// Downgrade write lock to read lock</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">processData</span><span class="hljs-params">()</span> </span>{
        lock.writeLock().lock();
        <span class="hljs-keyword">try</span> {
            <span class="hljs-comment">// Perform write operation</span>
            value = <span class="hljs-string">"processed"</span>;

            <span class="hljs-comment">// Acquire read lock before releasing write lock (downgrade)</span>
            lock.readLock().lock();
        } <span class="hljs-keyword">finally</span> {
            lock.writeLock().unlock();
        }

        <span class="hljs-keyword">try</span> {
            <span class="hljs-comment">// Now we only hold the read lock</span>
            System.out.println(<span class="hljs-string">"Current value: "</span> + value);
        } <span class="hljs-keyword">finally</span> {
            lock.readLock().unlock();
        }
    }
}
</code></pre>
<hr />
<h2 id="heading-semaphore-semaphore">Semaphore {#semaphore}</h2>
<h3 id="heading-overview-4">Overview</h3>
<p>A <code>Semaphore</code> maintains a set of permits. Threads call <code>acquire()</code> to wait for a permit and <code>release()</code> to release one. When no permits are available, <code>acquire()</code> blocks the thread.</p>
<h3 id="heading-characteristics-3">Characteristics</h3>
<ul>
<li><strong>Permit-Based</strong>: Controls access through a pool of permits</li>
<li><strong>Resource Pooling</strong>: Useful for limiting concurrent access to a resource pool</li>
<li><strong>Counting Semaphore</strong>: Maintains a count of permits</li>
<li><strong>Binary Semaphore</strong>: Acts as a lock when permit count = 1</li>
<li><strong>Non-Reentrant</strong>: By default, doesn't allow the same thread to acquire twice</li>
</ul>
<h3 id="heading-usage-3">Usage</h3>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.concurrent.Semaphore;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ConnectionPool</span> </span>{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> Semaphore semaphore = <span class="hljs-keyword">new</span> Semaphore(<span class="hljs-number">5</span>); <span class="hljs-comment">// 5 connections available</span>

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">executeTask</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> InterruptedException </span>{
        semaphore.acquire(); <span class="hljs-comment">// Wait for a permit</span>
        <span class="hljs-keyword">try</span> {
            System.out.println(<span class="hljs-string">"Executing task with connection"</span>);
            <span class="hljs-comment">// Simulate work</span>
            Thread.sleep(<span class="hljs-number">1000</span>);
        } <span class="hljs-keyword">finally</span> {
            semaphore.release(); <span class="hljs-comment">// Release the permit</span>
        }
    }
}
</code></pre>
<h3 id="heading-advantages-3">Advantages</h3>
<p>✅ Excellent for resource pooling<br />✅ Simple counting mechanism<br />✅ Can be used as a binary lock (Mutex)<br />✅ Supports timeout with <code>tryAcquire(long, TimeUnit)</code>  </p>
<h3 id="heading-disadvantages-3">Disadvantages</h3>
<p>❌ Not reentrant (unless you track permits manually)<br />❌ Less intuitive than locks for mutual exclusion<br />❌ No condition variables  </p>
<h3 id="heading-binary-semaphore-mutex">Binary Semaphore (Mutex)</h3>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.concurrent.Semaphore;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MutexExample</span> </span>{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> Semaphore mutex = <span class="hljs-keyword">new</span> Semaphore(<span class="hljs-number">1</span>); <span class="hljs-comment">// Binary semaphore</span>
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> counter = <span class="hljs-number">0</span>;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">incrementCounter</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> InterruptedException </span>{
        mutex.acquire();
        <span class="hljs-keyword">try</span> {
            counter++;
        } <span class="hljs-keyword">finally</span> {
            mutex.release();
        }
    }
}
</code></pre>
<hr />
<h2 id="heading-stampedlock-stampedlock">StampedLock {#stampedlock}</h2>
<h3 id="heading-overview-5">Overview</h3>
<p><code>StampedLock</code> is a high-performance lock introduced in Java 8 that provides three modes: write lock, read lock, and optimistic read. The optimistic read mode doesn't acquire a lock at all but checks a "stamp" to detect conflicts.</p>
<h3 id="heading-characteristics-4">Characteristics</h3>
<ul>
<li><strong>Optimistic Reading</strong>: Can read without acquiring a lock</li>
<li><strong>Stamp-Based Validation</strong>: Uses stamps to detect write conflicts</li>
<li><strong>High Performance</strong>: Designed for low-contention scenarios</li>
<li><strong>Three Modes</strong>: Optimistic read, pessimistic read, write</li>
<li><strong>Non-Reentrant</strong>: Cannot be reacquired by the same thread</li>
</ul>
<h3 id="heading-usage-4">Usage</h3>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.concurrent.locks.StampedLock;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">OptimizedData</span> </span>{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> value = <span class="hljs-number">0</span>;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> StampedLock lock = <span class="hljs-keyword">new</span> StampedLock();

    <span class="hljs-comment">// Optimistic read - fast path</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">readOptimistic</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">long</span> stamp = lock.tryOptimisticRead();
        <span class="hljs-keyword">int</span> result = value;

        <span class="hljs-keyword">if</span> (!lock.validate(stamp)) {
            <span class="hljs-comment">// Conflict detected, fall back to pessimistic read</span>
            stamp = lock.readLock();
            <span class="hljs-keyword">try</span> {
                result = value;
            } <span class="hljs-keyword">finally</span> {
                lock.unlockRead(stamp);
            }
        }
        <span class="hljs-keyword">return</span> result;
    }

    <span class="hljs-comment">// Pessimistic read</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">readPessimistic</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">long</span> stamp = lock.readLock();
        <span class="hljs-keyword">try</span> {
            <span class="hljs-keyword">return</span> value;
        } <span class="hljs-keyword">finally</span> {
            lock.unlockRead(stamp);
        }
    }

    <span class="hljs-comment">// Write lock</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">write</span><span class="hljs-params">(<span class="hljs-keyword">int</span> newValue)</span> </span>{
        <span class="hljs-keyword">long</span> stamp = lock.writeLock();
        <span class="hljs-keyword">try</span> {
            value = newValue;
        } <span class="hljs-keyword">finally</span> {
            lock.unlockWrite(stamp);
        }
    }
}
</code></pre>
<h3 id="heading-advantages-4">Advantages</h3>
<p>✅ Excellent performance for read-heavy, low-contention scenarios<br />✅ Optimistic read avoids blocking<br />✅ Lower overhead than ReentrantReadWriteLock  </p>
<h3 id="heading-disadvantages-4">Disadvantages</h3>
<p>❌ Not reentrant<br />❌ More complex API<br />❌ Should only be used when you understand the implications<br />❌ Optimistic reads can fail (need validation logic)  </p>
<hr />
<h2 id="heading-countdownlatch-countdownlatch">CountDownLatch {#countdownlatch}</h2>
<h3 id="heading-overview-6">Overview</h3>
<p><code>CountDownLatch</code> is a synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.</p>
<h3 id="heading-characteristics-5">Characteristics</h3>
<ul>
<li><strong>One-Time Use</strong>: Cannot be reset once count reaches zero</li>
<li><strong>Countdown Mechanism</strong>: Count decrements with each <code>countDown()</code> call</li>
<li><strong>Blocking Wait</strong>: <code>await()</code> blocks until count reaches zero</li>
<li><strong>Simple Coordination</strong>: Good for one-off synchronization</li>
</ul>
<h3 id="heading-usage-5">Usage</h3>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.concurrent.CountDownLatch;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ParallelProcessing</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> <span class="hljs-keyword">throws</span> InterruptedException </span>{
        <span class="hljs-keyword">int</span> numWorkers = <span class="hljs-number">3</span>;
        CountDownLatch latch = <span class="hljs-keyword">new</span> CountDownLatch(numWorkers);

        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; numWorkers; i++) {
            <span class="hljs-keyword">new</span> Thread(() -&gt; {
                System.out.println(Thread.currentThread().getName() + <span class="hljs-string">" is working"</span>);
                <span class="hljs-keyword">try</span> {
                    Thread.sleep(<span class="hljs-number">2000</span>);
                } <span class="hljs-keyword">catch</span> (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
                System.out.println(Thread.currentThread().getName() + <span class="hljs-string">" finished"</span>);
                latch.countDown();
            }).start();
        }

        latch.await(); <span class="hljs-comment">// Wait for all workers to finish</span>
        System.out.println(<span class="hljs-string">"All workers completed!"</span>);
    }
}
</code></pre>
<h3 id="heading-advantages-5">Advantages</h3>
<p>✅ Simple and intuitive for one-off synchronization<br />✅ Lightweight and efficient<br />✅ Supports timeout with <code>await(long, TimeUnit)</code>  </p>
<h3 id="heading-disadvantages-5">Disadvantages</h3>
<p>❌ Cannot be reused (count cannot be reset)<br />❌ Only useful for one-time events<br />❌ Not suitable for repeating synchronization  </p>
<hr />
<h2 id="heading-cyclicbarrier-cyclicbarrier">CyclicBarrier {#cyclicbarrier}</h2>
<h3 id="heading-overview-7">Overview</h3>
<p><code>CyclicBarrier</code> allows a fixed number of parties to wait for each other at a barrier point. Unlike <code>CountDownLatch</code>, it can be reused.</p>
<h3 id="heading-characteristics-6">Characteristics</h3>
<ul>
<li><strong>Reusable</strong>: Can be used multiple times (cyclic)</li>
<li><strong>Mutual Waiting</strong>: All threads wait for each other</li>
<li><strong>Barrier Action</strong>: Optional action executed when all parties arrive</li>
<li><strong>Fixed Number of Parties</strong>: Number of threads must be known upfront</li>
</ul>
<h3 id="heading-usage-6">Usage</h3>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.concurrent.CyclicBarrier;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">BarrierExample</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        <span class="hljs-keyword">int</span> numThreads = <span class="hljs-number">3</span>;
        CyclicBarrier barrier = <span class="hljs-keyword">new</span> CyclicBarrier(numThreads, () -&gt; {
            System.out.println(<span class="hljs-string">"All threads have reached the barrier!"</span>);
        });

        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; numThreads; i++) {
            <span class="hljs-keyword">new</span> Thread(() -&gt; {
                <span class="hljs-keyword">try</span> {
                    System.out.println(Thread.currentThread().getName() + <span class="hljs-string">" is working"</span>);
                    Thread.sleep((<span class="hljs-keyword">long</span>)(Math.random() * <span class="hljs-number">3000</span>));
                    System.out.println(Thread.currentThread().getName() + <span class="hljs-string">" reached barrier"</span>);
                    barrier.await(); <span class="hljs-comment">// Wait for others</span>
                    System.out.println(Thread.currentThread().getName() + <span class="hljs-string">" passed barrier"</span>);
                } <span class="hljs-keyword">catch</span> (Exception e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}
</code></pre>
<h3 id="heading-advantages-6">Advantages</h3>
<p>✅ Reusable (cyclic)<br />✅ Symmetric - all threads wait for each other<br />✅ Optional barrier action supports coordinated tasks<br />✅ Good for iterative synchronization  </p>
<h3 id="heading-disadvantages-6">Disadvantages</h3>
<p>❌ All threads must wait (no timeout)<br />❌ Breaking the barrier (exception) may cause issues<br />❌ Less flexible than Phaser  </p>
<hr />
<h2 id="heading-phaser-phaser">Phaser {#phaser}</h2>
<h3 id="heading-overview-8">Overview</h3>
<p><code>Phaser</code> is a more flexible version of <code>CyclicBarrier</code> and <code>CountDownLatch</code> combined. It supports dynamic party registration and can be reused across multiple phases.</p>
<h3 id="heading-characteristics-7">Characteristics</h3>
<ul>
<li><strong>Flexible Parties</strong>: Can dynamically register/deregister threads</li>
<li><strong>Multiple Phases</strong>: Can synchronize through multiple phases</li>
<li><strong>Phased Execution</strong>: Better control over multi-phase synchronization</li>
<li><strong>Timeout Support</strong>: Can timeout waiting for a phase to complete</li>
<li><strong>Terminal Phase</strong>: Can handle completion elegantly</li>
</ul>
<h3 id="heading-usage-7">Usage</h3>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.concurrent.Phaser;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PhaserExample</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        Phaser phaser = <span class="hljs-keyword">new</span> Phaser(<span class="hljs-number">1</span>); <span class="hljs-comment">// Register the main thread</span>

        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">3</span>; i++) {
            phaser.register(); <span class="hljs-comment">// Register each worker</span>
            <span class="hljs-keyword">new</span> Thread(() -&gt; {
                <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> phase = <span class="hljs-number">0</span>; phase &lt; <span class="hljs-number">3</span>; phase++) {
                    System.out.println(Thread.currentThread().getName() + 
                        <span class="hljs-string">" working on phase "</span> + phase);
                    <span class="hljs-keyword">try</span> {
                        Thread.sleep((<span class="hljs-keyword">long</span>)(Math.random() * <span class="hljs-number">2000</span>));
                    } <span class="hljs-keyword">catch</span> (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                    System.out.println(Thread.currentThread().getName() + 
                        <span class="hljs-string">" finished phase "</span> + phase);
                    phaser.arriveAndAwaitAdvance(); <span class="hljs-comment">// Move to next phase</span>
                }
            }).start();
        }

        phaser.arriveAndAwaitAdvance(); <span class="hljs-comment">// Advance from phase 0</span>
        System.out.println(<span class="hljs-string">"Phase 0 complete!"</span>);

        phaser.arriveAndAwaitAdvance(); <span class="hljs-comment">// Advance from phase 1</span>
        System.out.println(<span class="hljs-string">"Phase 1 complete!"</span>);

        phaser.arriveAndAwaitAdvance(); <span class="hljs-comment">// Advance from phase 2</span>
        System.out.println(<span class="hljs-string">"Phase 2 complete!"</span>);
    }
}
</code></pre>
<h3 id="heading-advantages-7">Advantages</h3>
<p>✅ Dynamic party registration<br />✅ Multiple phases support<br />✅ Timeout support with <code>awaitAdvanceInterruptibly()</code><br />✅ Elegant handling of completion<br />✅ Most flexible synchronization primitive  </p>
<h3 id="heading-disadvantages-7">Disadvantages</h3>
<p>❌ More complex API<br />❌ Slight overhead compared to simpler mechanisms<br />❌ Requires careful understanding of phase advancement  </p>
<hr />
<h2 id="heading-comparison-table-comparison-table">Comparison Table {#comparison-table}</h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Feature</td><td>Intrinsic Lock</td><td>ReentrantLock</td><td>ReadWriteLock</td><td>Semaphore</td><td>StampedLock</td><td>CountDownLatch</td><td>CyclicBarrier</td><td>Phaser</td></tr>
</thead>
<tbody>
<tr>
<td><strong>Mutual Exclusion</strong></td><td>✅</td><td>✅</td><td>✅ (Write)</td><td>✅</td><td>✅</td><td>❌</td><td>❌</td><td>❌</td></tr>
<tr>
<td><strong>Reentrancy</strong></td><td>✅</td><td>✅</td><td>✅</td><td>❌</td><td>❌</td><td>N/A</td><td>N/A</td><td>N/A</td></tr>
<tr>
<td><strong>Fairness Option</strong></td><td>❌</td><td>✅</td><td>✅</td><td>❌</td><td>❌</td><td>N/A</td><td>N/A</td><td>N/A</td></tr>
<tr>
<td><strong>Timeout Support</strong></td><td>❌</td><td>✅</td><td>✅</td><td>✅</td><td>✅</td><td>✅</td><td>❌</td><td>✅</td></tr>
<tr>
<td><strong>Interruptible</strong></td><td>❌</td><td>✅</td><td>✅</td><td>✅</td><td>❌</td><td>✅</td><td>❌</td><td>✅</td></tr>
<tr>
<td><strong>Conditions</strong></td><td>✅</td><td>✅</td><td>❌</td><td>❌</td><td>❌</td><td>❌</td><td>❌</td><td>❌</td></tr>
<tr>
<td><strong>Read-Write Separation</strong></td><td>❌</td><td>❌</td><td>✅</td><td>❌</td><td>✅</td><td>❌</td><td>❌</td><td>❌</td></tr>
<tr>
<td><strong>Concurrent Reads</strong></td><td>❌</td><td>❌</td><td>✅</td><td>❌</td><td>✅</td><td>N/A</td><td>N/A</td><td>N/A</td></tr>
<tr>
<td><strong>Reusable</strong></td><td>✅</td><td>✅</td><td>✅</td><td>✅</td><td>✅</td><td>❌</td><td>✅</td><td>✅</td></tr>
<tr>
<td><strong>Dynamic Parties</strong></td><td>N/A</td><td>N/A</td><td>N/A</td><td>N/A</td><td>N/A</td><td>N/A</td><td>❌</td><td>✅</td></tr>
<tr>
<td><strong>Multiple Phases</strong></td><td>N/A</td><td>N/A</td><td>N/A</td><td>N/A</td><td>N/A</td><td>❌</td><td>✅</td><td>✅</td></tr>
<tr>
<td><strong>Performance</strong></td><td>⚡⚡⚡</td><td>⚡⚡</td><td>⚡⚡</td><td>⚡⚡⚡</td><td>⚡⚡⚡⚡</td><td>⚡⚡⚡</td><td>⚡⚡⚡</td><td>⚡⚡⚡</td></tr>
<tr>
<td><strong>Complexity</strong></td><td>⭐</td><td>⭐⭐</td><td>⭐⭐</td><td>⭐⭐</td><td>⭐⭐⭐</td><td>⭐</td><td>⭐⭐</td><td>⭐⭐⭐</td></tr>
</tbody>
</table>
</div><hr />
<h2 id="heading-best-practices-best-practices">Best Practices {#best-practices}</h2>
<h3 id="heading-1-choose-the-right-tool">1. <strong>Choose the Right Tool</strong></h3>
<ul>
<li><strong>Simple mutual exclusion</strong>: Use <code>synchronized</code> for simplicity</li>
<li><strong>Advanced locking needs</strong>: Use <code>ReentrantLock</code> for flexibility</li>
<li><strong>Read-heavy workloads</strong>: Use <code>ReadWriteLock</code> or <code>StampedLock</code></li>
<li><strong>Resource pooling</strong>: Use <code>Semaphore</code></li>
<li><strong>One-time coordination</strong>: Use <code>CountDownLatch</code></li>
<li><strong>Iterative synchronization</strong>: Use <code>CyclicBarrier</code></li>
<li><strong>Multi-phase synchronization</strong>: Use <code>Phaser</code></li>
</ul>
<h3 id="heading-2-always-release-locks">2. <strong>Always Release Locks</strong></h3>
<pre><code class="lang-java">Lock lock = <span class="hljs-keyword">new</span> ReentrantLock();
lock.lock();
<span class="hljs-keyword">try</span> {
    <span class="hljs-comment">// Critical section</span>
} <span class="hljs-keyword">finally</span> {
    lock.unlock(); <span class="hljs-comment">// Always execute in finally</span>
}
</code></pre>
<h3 id="heading-3-avoid-deadlocks">3. <strong>Avoid Deadlocks</strong></h3>
<pre><code class="lang-java"><span class="hljs-comment">// ❌ BAD: Risk of deadlock with nested locks</span>
lock1.lock();
lock2.lock();

<span class="hljs-comment">// ✅ GOOD: Consistent lock ordering</span>
<span class="hljs-keyword">if</span> (lock1.getId() &lt; lock2.getId()) {
    lock1.lock();
    lock2.lock();
} <span class="hljs-keyword">else</span> {
    lock2.lock();
    lock1.lock();
}
</code></pre>
<h3 id="heading-4-use-try-finally-or-try-with-resources">4. <strong>Use Try-Finally or Try-With-Resources</strong></h3>
<pre><code class="lang-java"><span class="hljs-comment">// ✅ GOOD: Modern approach with try-with-resources (if available)</span>
<span class="hljs-keyword">try</span> (Locker locked = <span class="hljs-keyword">new</span> Locker(lock)) {
    <span class="hljs-comment">// Critical section</span>
}

<span class="hljs-comment">// ✅ GOOD: Traditional try-finally</span>
lock.lock();
<span class="hljs-keyword">try</span> {
    <span class="hljs-comment">// Critical section</span>
} <span class="hljs-keyword">finally</span> {
    lock.unlock();
}
</code></pre>
<h3 id="heading-5-consider-high-level-abstractions">5. <strong>Consider High-Level Abstractions</strong></h3>
<pre><code class="lang-java"><span class="hljs-comment">// ❌ Low-level: Manual synchronization</span>
<span class="hljs-comment">// ✅ High-level: Collections.synchronizedList or ConcurrentHashMap</span>
List&lt;String&gt; list = Collections.synchronizedList(<span class="hljs-keyword">new</span> ArrayList&lt;&gt;());
</code></pre>
<h3 id="heading-6-profile-before-optimizing">6. <strong>Profile Before Optimizing</strong></h3>
<p>StampedLock and other advanced locks introduce complexity. Profile your application to ensure the performance gains justify the complexity.</p>
<pre><code class="lang-java"><span class="hljs-comment">// ❌ Premature optimization</span>
<span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> StampedLock lock = <span class="hljs-keyword">new</span> StampedLock(); <span class="hljs-comment">// Might be overkill</span>

<span class="hljs-comment">// ✅ Thoughtful choice based on workload analysis</span>
<span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> ReentrantReadWriteLock lock = <span class="hljs-keyword">new</span> ReentrantReadWriteLock(); <span class="hljs-comment">// Suitable for the workload</span>
</code></pre>
<h3 id="heading-7-document-lock-ordering">7. <strong>Document Lock Ordering</strong></h3>
<pre><code class="lang-java"><span class="hljs-comment">/**
 * Locks must be acquired in this order to prevent deadlocks:
 * 1. accountLock
 * 2. transactionLock
 */</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">transfer</span><span class="hljs-params">(Account from, Account to, <span class="hljs-keyword">double</span> amount)</span> </span>{
    <span class="hljs-comment">// Lock in documented order</span>
}
</code></pre>
<h3 id="heading-8-use-javautilconcurrent-collections">8. <strong>Use java.util.concurrent Collections</strong></h3>
<pre><code class="lang-java"><span class="hljs-comment">// ✅ Preferred: Concurrent collections handle synchronization internally</span>
Map&lt;String, Integer&gt; map = <span class="hljs-keyword">new</span> ConcurrentHashMap&lt;&gt;();
List&lt;String&gt; list = <span class="hljs-keyword">new</span> CopyOnWriteArrayList&lt;&gt;();
Queue&lt;String&gt; queue = <span class="hljs-keyword">new</span> ConcurrentLinkedQueue&lt;&gt;();
</code></pre>
<hr />
<h2 id="heading-summary">Summary</h2>
<p>Java provides multiple synchronization mechanisms, each suited for different scenarios:</p>
<ul>
<li><strong><code>synchronized</code> (Intrinsic Locks)</strong>: Simple, built-in, suitable for basic synchronization</li>
<li><strong><code>ReentrantLock</code></strong>: Flexible, feature-rich alternative to synchronized with timeout and interruptibility</li>
<li><strong><code>ReadWriteLock</code></strong>: Optimized for read-heavy workloads with concurrent readers</li>
<li><strong><code>Semaphore</code></strong>: Perfect for resource pooling and limiting concurrent access</li>
<li><strong><code>StampedLock</code></strong>: High-performance option for low-contention scenarios with optimistic reads</li>
<li><strong><code>CountDownLatch</code></strong>: Simple one-time synchronization for waiting on completion</li>
<li><strong><code>CyclicBarrier</code></strong>: For reusable barrier points where threads wait for each other</li>
<li><strong><code>Phaser</code></strong>: Most flexible for multi-phase, dynamic synchronization scenarios</li>
</ul>
<p>The key is understanding your workload and choosing the appropriate primitive that provides the necessary functionality with minimal complexity. In most cases, simple solutions like <code>synchronized</code> or the concurrent collections are sufficient and preferable.</p>
<hr />
<h2 id="heading-interactive-demos">Interactive Demos</h2>
<p>This blog post comes with comprehensive, runnable demonstrations of each synchronization mechanism. Each demo includes:</p>
<ul>
<li><strong>Real-world scenarios</strong> (bank accounts, caches, connection pools, pipelines, game rounds)</li>
<li><strong>Best practices</strong> with detailed comments</li>
<li><strong>Multiple example classes</strong> per synchronization type</li>
<li><strong>Performance comparisons</strong> where applicable</li>
<li><strong>Exception handling</strong> and timeout patterns</li>
</ul>
<h3 id="heading-demo-files">Demo Files</h3>
<ol>
<li><strong>IntrinsicLockDemo</strong> - Bank accounts, thread-safe counters, and caches</li>
<li><strong>ReentrantLockDemo</strong> - Timeout support, producer-consumer queues, and fair scheduling</li>
<li><strong>ReadWriteLockDemo</strong> - Concurrent readers with performance comparison</li>
<li><strong>SemaphoreDemo</strong> - Connection pooling, rate limiting, and thread pool control</li>
<li><strong>StampedLockDemo</strong> - Optimistic reads with pessimistic fallback</li>
<li><strong>CountDownLatchDemo</strong> - Parallel task execution and pipeline coordination</li>
<li><strong>CyclicBarrierDemo</strong> - Iterative processing and game round synchronization</li>
<li><strong>PhaserDemo</strong> - Multi-phase execution and dynamic party management</li>
</ol>
<h3 id="heading-running-the-demos">Running the Demos</h3>
<p>Run the interactive launcher:</p>
<pre><code class="lang-bash">java info.mnafshin.locks_in_java.demos.DemoLauncher
</code></pre>
<p>Or run individual demos:</p>
<pre><code class="lang-bash">java info.mnafshin.locks_in_java.demos.IntrinsicLockDemo
java info.mnafshin.locks_in_java.demos.ReentrantLockDemo
java info.mnafshin.locks_in_java.demos.SemaphoreDemo
<span class="hljs-comment"># ... etc</span>
</code></pre>
<p>See <a target="_blank" href="DEMOS_README.md">DEMOS_README.md</a> for detailed documentation and usage instructions for each demo.</p>
<hr />
<h2 id="heading-further-reading">Further Reading</h2>
<ul>
<li>Java Concurrency in Practice (Book)</li>
<li>Java API Documentation: <code>java.util.concurrent</code> package</li>
<li>Oracle Java Tutorials on Concurrency</li>
</ul>
<hr />
<h2 id="heading-get-the-code">Get the Code</h2>
<p>The source code for this project is available on GitHub: 
https://github.com/mnafshin/locks-in-java.git</p>
]]></content:encoded></item><item><title><![CDATA[Debugging Java SSL/TLS Connections: A Guide to javax.net.debug]]></title><description><![CDATA[Debug Java SSL/TLS use `javax.net.debug` for handshake analysis and secure communication]]></description><link>https://springuniverse.hashnode.dev/debugging-java-ssltls-connections-a-guide-to-javaxnetdebug</link><guid isPermaLink="true">https://springuniverse.hashnode.dev/debugging-java-ssltls-connections-a-guide-to-javaxnetdebug</guid><category><![CDATA[SSL]]></category><category><![CDATA[debugging]]></category><category><![CDATA[troubleshooting]]></category><dc:creator><![CDATA[Afshin Amini]]></dc:creator><pubDate>Fri, 23 Jan 2026 17:10:22 GMT</pubDate><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>Understanding SSL/TLS handshakes is crucial for debugging secure connections in Java applications. In this guide, I'll walk you through a real-world example of capturing and analyzing an SSL/TLS handshake using Java's built-in debugging capabilities.</p>
<p>This article covers:</p>
<ul>
<li>How to enable SSL/TLS debugging in Java</li>
<li>Real handshake flow with detailed timing</li>
<li>Complete working example with <code>HttpURLConnection</code></li>
<li>Step-by-step breakdown of the TLS 1.2 handshake</li>
</ul>
<hr />
<h2 id="heading-enabling-ssltls-debug-output">Enabling SSL/TLS Debug Output</h2>
<p>To capture SSL/TLS debugging information, simply set this system property before establishing any connections:</p>
<pre><code class="lang-java">System.setProperty(<span class="hljs-string">"javax.net.debug"</span>, <span class="hljs-string">"all"</span>);
</code></pre>
<p>This enables comprehensive logging of:</p>
<ul>
<li>Cipher suite negotiation</li>
<li>Certificate validation</li>
<li>Handshake messages</li>
<li>Raw bytes sent/received</li>
<li>Session information</li>
</ul>
<h2 id="heading-real-world-tls-12-handshake-flow">Real-World TLS 1.2 Handshake Flow</h2>
<p>When you connect to an HTTPS endpoint (in our example: <code>https://httpbin.org/get</code>), the following handshake occurs:</p>
<h3 id="heading-ascii-diagram-complete-tls-12-handshake">ASCII Diagram: Complete TLS 1.2 Handshake</h3>
<pre><code>CLIENT (Java App)                           SERVER (httpbin.org)
════════════════════════════════════════════════════════════════

        ┌─────────────────────────────────┐
        │  <span class="hljs-number">1.</span> ClientHello                 │
        │  (<span class="hljs-number">22</span>:<span class="hljs-number">20</span>:<span class="hljs-number">06.819</span> CET)             │
        │  - Ciphers, Extensions          │
        │  - Random value                 │
        └────────────────────┬────────────┘
                             │
                             │ [Raw write]
                             │ TLS <span class="hljs-number">1.2</span> record
                             ├──────────────────────────────────&gt;
                                                                │
                                           ┌────────────────────┘
                                           │
                                           ▼
                            ┌──────────────────────────────────┐
                            │  <span class="hljs-number">2.</span> ServerHello                  │
                            │  (<span class="hljs-number">22</span>:<span class="hljs-number">20</span>:<span class="hljs-number">06.924</span> CET)              │
                            │  - Selected cipher suite:        │
                            │    TLS_ECDHE_RSA_WITH_AES_128... │
                            │  - Server random                 │
                            │  - Session ID                    │
                            └────────────────┬──────────────────┘
                                             │
                                             │ [Raw read]
        ┌────────────────────────────────────┤
        │                                     │
        ▼                                     ▼
┌──────────────────────────────┐  ┌──────────────────────────────────┐
│  <span class="hljs-number">3.</span> Server Certificate       │  │  <span class="hljs-number">4.</span> ServerKeyExchange (ECDH)     │
│  (<span class="hljs-number">22</span>:<span class="hljs-number">20</span>:<span class="hljs-number">06.930</span> CET)          │  │  (<span class="hljs-number">22</span>:<span class="hljs-number">20</span>:<span class="hljs-number">06.950</span> CET)              │
│  - Certificate chain:        │  │  - ECDH parameters               │
│    └─ httpbin.org            │  │  - Server<span class="hljs-string">'s ECDH public key      │
│    └─ Amazon RSA 2048 M      │  │  - Signature                     │
│    └─ Root CA                │  │                                  │
└──────────────────────────────┘  └──────────────────────────────────┘
        │                                    │
        └────────────────────┬───────────────┘
                             │
                             ▼
                    ┌──────────────────────┐
                    │  5. ServerHelloDone  │
                    │  (22:20:06.951 CET)  │
                    └────────┬─────────────┘
                             │
                             │ [Raw read]
        ┌────────────────────┘
        │
        ▼
┌───────────────────────────────────────────┐
│  6. ClientKeyExchange (ECDHE)             │
│  (22:20:06.951 CET)                       │
│  - Client'</span>s ECDH public key               │
│  - Compute shared secret (PreMasterKey)   │
└────────────────┬────────────────────────────┐
                 │                            │
                 │ [Raw write]                │
                 │ TLS <span class="hljs-number">1.2</span> handshake         │
                 ├───────────────────────────────────────────────&gt;
                 │                            │
                 ▼                            │
┌────────────────────────────────────────┐   │
│  <span class="hljs-number">7.</span> ChangeCipherSpec (Client)          │   │
│  (<span class="hljs-number">22</span>:<span class="hljs-number">20</span>:<span class="hljs-number">06.952</span> CET)                    │   │
│  - Switch to encrypted traffic         │   │
└────────────────┬─────────────────────────┐ │
                 │                          │ │
                 │ [Raw write]              │ │
                 │ TLS <span class="hljs-number">1.2</span> change spec      │ │
                 ├──────────────────────────────&gt;
                 │                          │ │
                 ▼                          │ │
┌────────────────────────────────────────┐   │
│  <span class="hljs-number">8.</span> Finished (Client)                  │   │
│  (<span class="hljs-number">22</span>:<span class="hljs-number">20</span>:<span class="hljs-number">06.954</span> CET)                    │   │
│  - MAC <span class="hljs-keyword">of</span> all handshake messages       │   │
│  - Encrypted <span class="hljs-keyword">with</span> session key          │   │
└────────────────┬─────────────────────────┐ │
                 │                          │ │
                 │ [Raw write]              │ │
                 │ TLS <span class="hljs-number">1.2</span> handshake       │ │
                 ├──────────────────────────────&gt;
                 │                          │ │
                 │                          │ │
                 │                   ┌──────┘ │
                 │                   │        │
                 │                   ▼        ▼
                 │        ┌──────────────────────────────┐
                 │        │  <span class="hljs-number">9.</span> NewSessionTicket         │
                 │        │  (<span class="hljs-number">22</span>:<span class="hljs-number">20</span>:<span class="hljs-number">07.056</span> CET)          │
                 │        │  - For session resumption    │
                 │        └────────┬─────────────────────┘
                 │                 │
                 │                 │ [Raw read]
        ┌────────┴─────────────────┤
        │                          │
        ▼                          ▼
┌──────────────────────┐  ┌────────────────────────────┐
│  <span class="hljs-number">10.</span> ChangeCipherSpec│  │  <span class="hljs-number">11.</span> Server Finished       │
│  (Server)            │  │  (<span class="hljs-number">22</span>:<span class="hljs-number">20</span>:<span class="hljs-number">07.056</span> CET)       │
│  (<span class="hljs-number">22</span>:<span class="hljs-number">20</span>:<span class="hljs-number">07.056</span> CET)  │  │  - MAC <span class="hljs-keyword">of</span> all handshake   │
└──────────────────────┘  │  - Encrypted <span class="hljs-keyword">with</span> key     │
                          └────────┬──────────────────┘
                                   │
                                   │ [Raw read]
                    ┌──────────────┘
                    │
                    ▼
        ┌───────────────────────────────┐
        │  ✓ HANDSHAKE COMPLETE        │
        │  (<span class="hljs-number">22</span>:<span class="hljs-number">20</span>:<span class="hljs-number">07.057</span> CET)          │
        │                              │
        │  Secure Channel Established  │
        │  - Ready <span class="hljs-keyword">for</span> application     │
        │  - All data encrypted/MAC<span class="hljs-string">'d  │
        └───────────────────────────────┘</span>
</code></pre><h3 id="heading-handshake-timing-amp-summary">Handshake Timing &amp; Summary</h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Step</td><td>Message Type</td><td>Direction</td><td>Timestamp</td><td>Duration</td></tr>
</thead>
<tbody>
<tr>
<td>1</td><td>ClientHello</td><td>Client → Server</td><td>22:20:06.819</td><td>-</td></tr>
<tr>
<td>2</td><td>ServerHello</td><td>Server → Client</td><td>22:20:06.924</td><td>+105ms</td></tr>
<tr>
<td>3</td><td>Certificate</td><td>Server → Client</td><td>22:20:06.930</td><td>+6ms</td></tr>
<tr>
<td>4</td><td>ServerKeyExchange</td><td>Server → Client</td><td>22:20:06.950</td><td>+20ms</td></tr>
<tr>
<td>5</td><td>ServerHelloDone</td><td>Server → Client</td><td>22:20:06.951</td><td>+1ms</td></tr>
<tr>
<td>6</td><td>ClientKeyExchange</td><td>Client → Server</td><td>22:20:06.951</td><td>-</td></tr>
<tr>
<td>7</td><td>ChangeCipherSpec</td><td>Client → Server</td><td>22:20:06.952</td><td>+1ms</td></tr>
<tr>
<td>8</td><td>Finished</td><td>Client → Server</td><td>22:20:06.954</td><td>+2ms</td></tr>
<tr>
<td>9</td><td>NewSessionTicket</td><td>Server → Client</td><td>22:20:07.056</td><td>+102ms</td></tr>
<tr>
<td>10</td><td>ChangeCipherSpec</td><td>Server → Client</td><td>22:20:07.056</td><td>-</td></tr>
<tr>
<td>11</td><td>Finished</td><td>Server → Client</td><td>22:20:07.056</td><td>-</td></tr>
<tr>
<td><strong>Total Duration</strong></td><td></td><td></td><td><strong>22:20:07.057</strong></td><td><strong>~238ms</strong></td></tr>
</tbody>
</table>
</div><h3 id="heading-negotiated-security-parameters">Negotiated Security Parameters</h3>
<ul>
<li><strong>Protocol Version</strong>: TLS 1.2</li>
<li><strong>Cipher Suite</strong>: <code>TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256</code> (0xC02F)</li>
<li><strong>Key Exchange</strong>: ECDHE (Elliptic Curve Diffie-Hellman Ephemeral)</li>
<li><strong>Encryption</strong>: AES-128-GCM</li>
<li><strong>Hash Algorithm</strong>: SHA256</li>
<li><strong>Server Certificate</strong>: httpbin.org (issued by Amazon RSA 2048 M)</li>
</ul>
<h3 id="heading-negotiated-extensions">Negotiated Extensions</h3>
<ul>
<li>✓ <code>renegotiation_info</code> - Controls renegotiation</li>
<li>✓ <code>server_name</code> - SNI (Server Name Indication)</li>
<li>✓ <code>ec_point_formats</code> - Supported EC point formats (uncompressed)</li>
<li>✓ <code>extended_master_secret</code> - Enhanced security</li>
<li>✓ <code>session_ticket</code> - Session resumption capability</li>
</ul>
<hr />
<h2 id="heading-handshake-phase-breakdown">Handshake Phase Breakdown</h2>
<h3 id="heading-phase-1-key-exchange-amp-authentication">Phase 1: Key Exchange &amp; Authentication</h3>
<p>The client and server exchange their capabilities and parameters:</p>
<ol>
<li><strong>ClientHello</strong> → Client offers supported ciphers, TLS versions, and extensions</li>
<li><strong>ServerHello</strong> → Server selects cipher, version, and confirms capabilities</li>
<li><strong>Certificate</strong> → Server proves identity with certificate chain</li>
<li><strong>ServerKeyExchange</strong> → Server sends ECDH parameters for key agreement</li>
<li><strong>ServerHelloDone</strong> → Marks end of server's initial messages</li>
</ol>
<h3 id="heading-phase-2-key-derivation">Phase 2: Key Derivation</h3>
<p>Both sides generate the shared secret:</p>
<ol start="6">
<li><strong>ClientKeyExchange</strong> → Client sends ECDH public key<ul>
<li>Both sides compute: <code>PreMasterSecret = ECDH(client_key, server_key)</code></li>
<li>Both derive: <code>MasterSecret = PRF(PreMasterSecret, "master secret", client_random || server_random)</code></li>
<li>Both generate session encryption/decryption keys</li>
</ul>
</li>
</ol>
<h3 id="heading-phase-3-cipher-activation-amp-verification">Phase 3: Cipher Activation &amp; Verification</h3>
<p>Both sides verify the handshake and activate encryption:</p>
<ol start="7">
<li><strong>ChangeCipherSpec (Client)</strong> → "Start encrypting from now on"</li>
<li><strong>Finished (Client)</strong> → Encrypted MAC of all handshake messages</li>
<li><strong>NewSessionTicket (Server)</strong> → Optional ticket for future session resumption</li>
<li><strong>ChangeCipherSpec (Server)</strong> → "Start encrypting from now on"</li>
<li><strong>Finished (Server)</strong> → Encrypted MAC of all handshake messages</li>
</ol>
<h3 id="heading-phase-4-secure-communication">Phase 4: Secure Communication</h3>
<p>Application data is now encrypted using the derived session keys.</p>
<hr />
<h2 id="heading-complete-working-example">Complete Working Example</h2>
<p>Here's the complete Java code that produces the above handshake:</p>
<h3 id="heading-appjava-main-application">App.java - Main Application</h3>
<pre><code class="lang-java"><span class="hljs-comment">/*
 * This source file was generated by the Gradle 'init' task
 */</span>
<span class="hljs-keyword">package</span> ssl.debug;

<span class="hljs-keyword">import</span> ssl.debug.adapter.BasicHttpsClient;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">App</span> </span>{

    BasicHttpsClient basicHttpsClient = <span class="hljs-keyword">new</span> BasicHttpsClient();

    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getGreeting</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> Exception </span>{
        <span class="hljs-keyword">return</span> basicHttpsClient.get(<span class="hljs-string">"https://httpbin.org/get"</span>);
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getSslInfo</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> Exception </span>{
        <span class="hljs-keyword">return</span> basicHttpsClient.getSSLInfo(<span class="hljs-string">"https://httpbin.org/get"</span>);
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> <span class="hljs-keyword">throws</span> Exception </span>{
        System.setProperty(<span class="hljs-string">"javax.net.debug"</span>, <span class="hljs-string">"all"</span>);
        App app = <span class="hljs-keyword">new</span> App();
        System.out.println(app.getGreeting());
        System.out.println(app.getSslInfo());
    }
}
</code></pre>
<h3 id="heading-basichttpsclientjava-https-client-library">BasicHttpsClient.java - HTTPS Client Library</h3>
<pre><code class="lang-java"><span class="hljs-keyword">package</span> ssl.debug.adapter;

<span class="hljs-keyword">import</span> java.io.BufferedReader;
<span class="hljs-keyword">import</span> java.io.InputStreamReader;
<span class="hljs-keyword">import</span> java.net.HttpURLConnection;
<span class="hljs-keyword">import</span> java.net.URI;
<span class="hljs-keyword">import</span> java.net.URL;
<span class="hljs-keyword">import</span> java.nio.charset.StandardCharsets;
<span class="hljs-keyword">import</span> java.util.List;
<span class="hljs-keyword">import</span> java.util.Map;

<span class="hljs-comment">/**
 * A simple HTTPS client for making secure HTTP requests.
 * Useful for demonstrating SSL/TLS handshake and debugging.
 */</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">BasicHttpsClient</span> </span>{

    <span class="hljs-keyword">private</span> String userAgent = <span class="hljs-string">"Mozilla/5.0 (Java SSL Debug)"</span>;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> connectionTimeout = <span class="hljs-number">10000</span>; <span class="hljs-comment">// 10 seconds</span>
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> readTimeout = <span class="hljs-number">10000</span>; <span class="hljs-comment">// 10 seconds</span>

    <span class="hljs-comment">/**
     * Performs a GET request to the specified URL
     * 
     * <span class="hljs-doctag">@param</span> urlString The HTTPS URL to connect to
     * <span class="hljs-doctag">@return</span> The response body as a string
     * <span class="hljs-doctag">@throws</span> Exception if connection fails
     */</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">get</span><span class="hljs-params">(String urlString)</span> <span class="hljs-keyword">throws</span> Exception </span>{
        <span class="hljs-keyword">return</span> get(urlString, <span class="hljs-keyword">null</span>);
    }

    <span class="hljs-comment">/**
     * Performs a GET request with custom headers
     * 
     * <span class="hljs-doctag">@param</span> urlString The HTTPS URL to connect to
     * <span class="hljs-doctag">@param</span> headers Custom headers to send (can be null)
     * <span class="hljs-doctag">@return</span> The response body as a string
     * <span class="hljs-doctag">@throws</span> Exception if connection fails
     */</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">get</span><span class="hljs-params">(String urlString, Map&lt;String, String&gt; headers)</span> <span class="hljs-keyword">throws</span> Exception </span>{
        HttpURLConnection connection = <span class="hljs-keyword">null</span>;
        <span class="hljs-keyword">try</span> {
            URL url = <span class="hljs-keyword">new</span> URI(urlString).toURL();
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod(<span class="hljs-string">"GET"</span>);
            connection.setConnectTimeout(connectionTimeout);
            connection.setReadTimeout(readTimeout);
            connection.setRequestProperty(<span class="hljs-string">"User-Agent"</span>, userAgent);

            <span class="hljs-comment">// Add custom headers if provided</span>
            <span class="hljs-keyword">if</span> (headers != <span class="hljs-keyword">null</span>) {
                headers.forEach(connection::setRequestProperty);
            }

            <span class="hljs-keyword">int</span> responseCode = connection.getResponseCode();
            String responseBody = readResponse(connection);

            System.out.println(<span class="hljs-string">"Status Code: "</span> + responseCode);
            System.out.println(<span class="hljs-string">"Response Headers:"</span>);
            printHeaders(connection.getHeaderFields());

            <span class="hljs-keyword">return</span> responseBody;

        } <span class="hljs-keyword">finally</span> {
            <span class="hljs-keyword">if</span> (connection != <span class="hljs-keyword">null</span>) {
                connection.disconnect();
            }
        }
    }

    <span class="hljs-comment">/**
     * Gets SSL/TLS information from the connection
     * 
     * <span class="hljs-doctag">@param</span> urlString The HTTPS URL to connect to
     * <span class="hljs-doctag">@return</span> SSL information as a formatted string
     * <span class="hljs-doctag">@throws</span> Exception if connection fails
     */</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getSSLInfo</span><span class="hljs-params">(String urlString)</span> <span class="hljs-keyword">throws</span> Exception </span>{
        HttpURLConnection connection = <span class="hljs-keyword">null</span>;
        <span class="hljs-keyword">try</span> {
            URL url = <span class="hljs-keyword">new</span> URI(urlString).toURL();
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod(<span class="hljs-string">"HEAD"</span>);
            connection.setConnectTimeout(connectionTimeout);
            connection.setReadTimeout(readTimeout);

            <span class="hljs-comment">// Trigger connection to perform SSL handshake</span>
            connection.getResponseCode();

            StringBuilder info = <span class="hljs-keyword">new</span> StringBuilder();
            info.append(<span class="hljs-string">"=== SSL/TLS Information ===\n"</span>);
            info.append(<span class="hljs-string">"URL: "</span>).append(urlString).append(<span class="hljs-string">"\n"</span>);
            info.append(<span class="hljs-string">"Status Code: "</span>).append(connection.getResponseCode()).append(<span class="hljs-string">"\n"</span>);
            info.append(<span class="hljs-string">"Content Type: "</span>).append(connection.getContentType()).append(<span class="hljs-string">"\n"</span>);

            <span class="hljs-comment">// Get cipher suite if available (only on HTTPS)</span>
            <span class="hljs-keyword">if</span> (connection <span class="hljs-keyword">instanceof</span> javax.net.ssl.HttpsURLConnection httpsConnection) {
                httpsConnection.connect();
                info.append(<span class="hljs-string">"Cipher Suite: "</span>).append(httpsConnection.getCipherSuite()).append(<span class="hljs-string">"\n"</span>);
                <span class="hljs-keyword">var</span> sslSession = httpsConnection.getSSLSession();
                <span class="hljs-keyword">if</span> (sslSession.isPresent()) {
                    info.append(<span class="hljs-string">"Protocol: "</span>).append(sslSession.get().getProtocol()).append(<span class="hljs-string">"\n"</span>);
                }
            }

            <span class="hljs-keyword">return</span> info.toString();

        } <span class="hljs-keyword">finally</span> {
            <span class="hljs-keyword">if</span> (connection != <span class="hljs-keyword">null</span>) {
                connection.disconnect();
            }
        }
    }

    <span class="hljs-comment">/**
     * Reads the response body from the connection
     */</span>
    <span class="hljs-function"><span class="hljs-keyword">private</span> String <span class="hljs-title">readResponse</span><span class="hljs-params">(HttpURLConnection connection)</span> <span class="hljs-keyword">throws</span> Exception </span>{
        StringBuilder response = <span class="hljs-keyword">new</span> StringBuilder();
        <span class="hljs-keyword">try</span> (BufferedReader reader = <span class="hljs-keyword">new</span> BufferedReader(
                <span class="hljs-keyword">new</span> InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
            String line;
            <span class="hljs-keyword">while</span> ((line = reader.readLine()) != <span class="hljs-keyword">null</span>) {
                response.append(line).append(<span class="hljs-string">"\n"</span>);
            }
        }
        <span class="hljs-keyword">return</span> response.toString();
    }

    <span class="hljs-comment">/**
     * Prints response headers
     */</span>
    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title">printHeaders</span><span class="hljs-params">(Map&lt;String, List&lt;String&gt;&gt; headers)</span> </span>{
        headers.forEach((key, values) -&gt; {
            <span class="hljs-keyword">if</span> (key != <span class="hljs-keyword">null</span>) { <span class="hljs-comment">// null key is the status line</span>
                values.forEach(value -&gt; System.out.println(<span class="hljs-string">"  "</span> + key + <span class="hljs-string">": "</span> + value));
            }
        });
    }

    <span class="hljs-comment">/**
     * Sets the connection timeout
     */</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setConnectionTimeout</span><span class="hljs-params">(<span class="hljs-keyword">int</span> timeout)</span> </span>{
        <span class="hljs-keyword">this</span>.connectionTimeout = timeout;
    }

    <span class="hljs-comment">/**
     * Sets the read timeout
     */</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setReadTimeout</span><span class="hljs-params">(<span class="hljs-keyword">int</span> timeout)</span> </span>{
        <span class="hljs-keyword">this</span>.readTimeout = timeout;
    }

    <span class="hljs-comment">/**
     * Sets the User-Agent header
     */</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setUserAgent</span><span class="hljs-params">(String userAgent)</span> </span>{
        <span class="hljs-keyword">this</span>.userAgent = userAgent;
    }
}
</code></pre>
<hr />
<h2 id="heading-how-to-run-the-example">How to Run the Example</h2>
<h3 id="heading-prerequisites">Prerequisites</h3>
<ul>
<li>Java 21+ (or JDK 17+ minimum)</li>
<li>Gradle 8.x</li>
</ul>
<h3 id="heading-steps">Steps</h3>
<ol>
<li><p><strong>Clone or download the project</strong>:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">cd</span> ssl-debug
</code></pre>
</li>
<li><p><strong>Build the project</strong>:</p>
<pre><code class="lang-bash">./gradlew build
</code></pre>
</li>
<li><p><strong>Run with SSL debugging enabled</strong>:</p>
<pre><code class="lang-bash">./gradlew run
</code></pre>
</li>
<li><p><strong>Capture output to file</strong>:</p>
<pre><code class="lang-bash">./gradlew run &gt; all.log 2&gt;&amp;1
</code></pre>
</li>
</ol>
<p>The application will:</p>
<ul>
<li>Enable <code>javax.net.debug=all</code></li>
<li>Make a GET request to <code>https://httpbin.org/get</code></li>
<li>Log all TLS handshake messages</li>
<li>Display SSL/TLS information (cipher suite, protocol version, etc.)</li>
</ul>
<hr />
<h2 id="heading-key-insights-from-the-handshake">Key Insights from the Handshake</h2>
<h3 id="heading-certificate-chain-validation">Certificate Chain Validation</h3>
<p>The SSL/TLS debug output shows the server provided three certificates:</p>
<ol>
<li><strong>End-Entity Certificate</strong>: httpbin.org (issued by Amazon RSA 2048 M CA)</li>
<li><strong>Intermediate CA</strong>: Amazon RSA 2048 M</li>
<li><strong>Root CA</strong>: Amazon Root CA (trusted in system trust store)</li>
</ol>
<p>The JVM validates this chain by:</p>
<ul>
<li>Loading 152 trusted CA certificates from <code>cacerts</code></li>
<li>Verifying each certificate's signature against its issuer</li>
<li>Checking validity dates</li>
<li>Confirming key usage extensions</li>
</ul>
<h3 id="heading-cipher-suite-selection">Cipher Suite Selection</h3>
<p>The server chose <code>TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256</code> because it's:</p>
<ul>
<li><strong>Secure</strong>: Modern encryption standard</li>
<li><strong>Forward-Secure</strong>: Uses ephemeral ECDH keys (PFS)</li>
<li><strong>Authenticated</strong>: RSA signature verification</li>
<li><strong>Authenticated Encryption</strong>: AES-GCM prevents tampering</li>
</ul>
<h3 id="heading-key-exchange-details">Key Exchange Details</h3>
<ul>
<li><strong>Algorithm</strong>: ECDHE (Elliptic Curve Diffie-Hellman Ephemeral)</li>
<li><strong>Benefits</strong>: <ul>
<li>Perfect Forward Secrecy (PFS) - past sessions are safe even if long-term keys are compromised</li>
<li>Faster than traditional DHE</li>
<li>Smaller key sizes with equivalent security</li>
</ul>
</li>
</ul>
<hr />
<h2 id="heading-common-ssltls-debugging-scenarios">Common SSL/TLS Debugging Scenarios</h2>
<h3 id="heading-debug-level-options">Debug Level Options</h3>
<pre><code class="lang-java"><span class="hljs-comment">// Full debug (as shown in this guide)</span>
System.setProperty(<span class="hljs-string">"javax.net.debug"</span>, <span class="hljs-string">"all"</span>);

<span class="hljs-comment">// Specific areas only</span>
System.setProperty(<span class="hljs-string">"javax.net.debug"</span>, <span class="hljs-string">"ssl"</span>);           <span class="hljs-comment">// SSL records</span>
System.setProperty(<span class="hljs-string">"javax.net.debug"</span>, <span class="hljs-string">"ssl:handshake"</span>); <span class="hljs-comment">// Handshake only</span>
System.setProperty(<span class="hljs-string">"javax.net.debug"</span>, <span class="hljs-string">"ssl:trustmanager"</span>); <span class="hljs-comment">// Certificate validation</span>
System.setProperty(<span class="hljs-string">"javax.net.debug"</span>, <span class="hljs-string">"ssl:record"</span>);    <span class="hljs-comment">// Record layer details</span>
</code></pre>
<h3 id="heading-troubleshooting-common-issues">Troubleshooting Common Issues</h3>
<p><strong>Issue</strong>: <code>PKIX path building failed</code></p>
<ul>
<li><strong>Cause</strong>: Certificate not in trust store</li>
<li><strong>Solution</strong>: Import certificate or use custom TrustManager</li>
</ul>
<p><strong>Issue</strong>: <code>Unsupported or unrecognized SSL message</code></p>
<ul>
<li><strong>Cause</strong>: Connecting to non-HTTPS endpoint</li>
<li><strong>Solution</strong>: Verify URL starts with <code>https://</code></li>
</ul>
<p><strong>Issue</strong>: <code>Excessive network latency</code></p>
<ul>
<li><strong>Cause</strong>: Certificate revocation checks (OCSP, CRL)</li>
<li><strong>Solution</strong>: Disable revocation checks if acceptable for your use case</li>
</ul>
<hr />
<h2 id="heading-conclusion">Conclusion</h2>
<p>Understanding TLS/TLS handshakes is essential for:</p>
<ul>
<li><strong>Debugging</strong>: Identifying connection issues quickly</li>
<li><strong>Security</strong>: Understanding what's being negotiated</li>
<li><strong>Performance</strong>: Analyzing handshake overhead</li>
<li><strong>Compliance</strong>: Verifying secure cipher suites are used</li>
</ul>
<p>The <code>javax.net.debug</code> system property provides deep visibility into Java's SSL/TLS layer, making it invaluable for developers working with secure connections.</p>
<p><strong>Remember</strong>: The SSL/TLS logs contain sensitive handshake information. Only enable debugging in development environments, never in production without careful security considerations.</p>
<hr />
<h2 id="heading-resources">Resources</h2>
<ul>
<li><a target="_blank" href="https://docs.oracle.com/javase/8/docs/technotes/guides/security/jsse/JSSERefGuide.html">Java JSSE Documentation</a></li>
<li><a target="_blank" href="https://tools.ietf.org/html/rfc5246">RFC 5246 - TLS 1.2</a></li>
<li><a target="_blank" href="https://cheatsheetseries.owasp.org/cheatsheets/Transport_Layer_Protection_Cheat_Sheet.html">OWASP Transport Layer Protection</a></li>
<li><a target="_blank" href="https://httpbin.org/">httpbin.org</a> - HTTP Request/Response Service</li>
</ul>
<hr />
<h2 id="heading-get-the-code">Get the Code</h2>
<p>The source code for this project is available on GitHub:</p>
<p><strong>📚 <a target="_blank" href="https://github.com/mnafshin/ssl-debug">github.com/mnafshin/ssl-debug</a></strong></p>
<p>Feel free to fork, clone, and experiment with the examples to deepen your understanding of SSL/TLS handshakes!</p>
]]></content:encoded></item></channel></rss>