<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Manidevs on Medium]]></title>
        <description><![CDATA[Stories by Manidevs on Medium]]></description>
        <link>https://medium.com/@manidevs96?source=rss-6cbf0ccd9b8b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*FQBMTvpn-SvE5q7e</url>
            <title>Stories by Manidevs on Medium</title>
            <link>https://medium.com/@manidevs96?source=rss-6cbf0ccd9b8b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 07:08:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@manidevs96/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[A Thread-Safe OAuth Token Cache for AEM Backend Integrations]]></title>
            <link>https://medium.com/@manidevs96/a-thread-safe-oauth-token-cache-for-aem-backend-integrations-ae5c3cbf2310?source=rss-6cbf0ccd9b8b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae5c3cbf2310</guid>
            <category><![CDATA[adobe-experience-manager]]></category>
            <category><![CDATA[caching]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[api-integration]]></category>
            <dc:creator><![CDATA[Manidevs]]></dc:creator>
            <pubDate>Mon, 24 Aug 2026 13:33:28 GMT</pubDate>
            <atom:updated>2026-08-24T13:33:28.051Z</atom:updated>
            <content:encoded><![CDATA[<p><em>One shared token, refreshed only when needed, safe under concurrent traffic.</em></p><p>If your AEM instance calls secured backend APIs using client-credentials OAuth, you’ve probably run into the same question: <strong>do I really need to fetch a new token for every call?</strong></p><p>You don’t. A single cached token, refreshed just before it expires and protected against concurrent refresh storms, is enough for almost every AEM backend integration — servlets calling external APIs, OSGi services orchestrating multiple backend calls per request, and scheduled jobs running on a timer.</p><p>This post walks through a production-ready pattern for that: one shared token service, an immutable token snapshot, double-checked locking for refresh, an early-refresh window, and a single retry on auth failure — plus the edge cases that tutorials usually skip.</p><h3>The Goal</h3><ol><li>Don’t request a token for every call.</li><li>Refresh only when needed.</li><li>Prevent concurrent refresh storms (five requests near expiry shouldn’t trigger five token calls).</li><li>Retry once when a token is rejected mid-flight.</li></ol><h3>The End-to-End Flow</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XHNrw2iAfqYJkG_cJIWNig.png" /></figure><h3>Step 1: Define a Shared Token Service</h3><p>Every backend caller should go through one OSGi service. Concurrency logic and retry logic live here — nowhere else.</p><pre>public interface TokenAuthService {<br>    String getValidAccessToken() throws IOException;<br>    void invalidateToken();</pre><pre>    @FunctionalInterface<br>    interface TokenRequestExecutor {<br>        HttpServiceResponse execute(String accessToken) throws IOException;<br>    }</pre><pre>    HttpServiceResponse executeWithFreshTokenRetry(TokenRequestExecutor requestExecutor) throws IOException;<br>}</pre><h3>Step 2: Store OAuth Config in OSGi Configuration</h3><pre>@ObjectClassDefinition(<br>    name = &quot;Backend Token Service Configuration&quot;,<br>    description = &quot;Global OAuth settings for token retrieval.&quot;<br>)<br>public @interface Configuration {<br>    String oauthClientId() default &quot;&quot;;<br>    String oauthClientSecret() default &quot;&quot;;<br>    String oauthTokenUrl() default &quot;&quot;;<br>    int oauthEarlyRefreshWindowSeconds() default 120;<br>    int oauthRefreshLockTimeoutSeconds() default 10;<br>    int oauthFailureCooldownSeconds() default 5;<br>}</pre><p>Two extra fields beyond the basics — oauthRefreshLockTimeoutSeconds and oauthFailureCooldownSeconds — show up in Steps 5 and 7 to close two gaps in the naive version of this pattern.</p><h3>Step 3: Wire Up the OSGi Lifecycle</h3><p>This is the part most write-ups skip, then readers have to guess at it. Here’s the activation and config-update wiring that ties everything together:</p><pre>@Component(service = TokenAuthService.class)<br>@Designate(ocd = Configuration.class)<br>public class TokenAuthServiceImpl implements TokenAuthService {</pre><pre>    private static final Logger LOG = LoggerFactory.getLogger(TokenAuthServiceImpl.class);</pre><pre>    private volatile TokenState tokenState;<br>    private volatile long lastFailureAt = 0L;<br>    private final ReentrantLock tokenLock = new ReentrantLock();</pre><pre>    private String oauthClientId;<br>    private String oauthClientSecret;<br>    private String oauthTokenUrl;<br>    private int oauthEarlyRefreshWindowSeconds;<br>    private int oauthRefreshLockTimeoutSeconds;<br>    private int oauthFailureCooldownSeconds;</pre><pre>    @Reference<br>    private TokenService tokenService;</pre><pre>    @Activate<br>    @Modified<br>    protected void activate(Configuration config) {<br>        this.oauthClientId = config.oauthClientId();<br>        this.oauthClientSecret = config.oauthClientSecret();<br>        this.oauthTokenUrl = config.oauthTokenUrl();<br>        this.oauthEarlyRefreshWindowSeconds = config.oauthEarlyRefreshWindowSeconds();<br>        this.oauthRefreshLockTimeoutSeconds = config.oauthRefreshLockTimeoutSeconds();<br>        this.oauthFailureCooldownSeconds = config.oauthFailureCooldownSeconds();</pre><pre>        LOG.info(&quot;Token service configured. clientId present: {}, tokenUrl present: {}&quot;,<br>            StringUtils.isNotBlank(oauthClientId), StringUtils.isNotBlank(oauthTokenUrl));</pre><pre>        // Config changed mid-flight (e.g. rotated secret) — drop any cached token<br>        // so the next call is forced to re-authenticate with the new credentials.<br>        tokenState = null;</pre><pre>        warmUpTokenCache();<br>    }<br>}</pre><p>@Modified matters as much as @Activate here: if someone rotates the client secret in OSGi config without a full bundle restart, you want the cached token invalidated immediately, not reused until it happens to expire.</p><h3>Step 4: Keep an Immutable Token Snapshot</h3><pre>private static final class TokenState {<br>    private final String accessToken;<br>    private final long issuedAt;<br>    private final long expiresAt;</pre><pre>    private TokenState(String accessToken, long issuedAt, long expiresAt) {<br>        this.accessToken = accessToken;<br>        this.issuedAt = issuedAt;<br>        this.expiresAt = expiresAt;<br>    }<br>}</pre><p>The token reference is volatile so a refresh thread can publish a new snapshot and every other thread sees it immediately, without needing to hold a lock just to <em>read</em> the token.</p><h3>Step 5: Implement getValidAccessToken</h3><pre>@Override<br>public String getValidAccessToken() throws IOException {<br>    validateRequiredInputs(oauthClientId, oauthClientSecret, oauthTokenUrl);</pre><pre>    TokenState current = tokenState;<br>    if (isTokenUsable(current, oauthEarlyRefreshWindowSeconds)) {<br>        return current.accessToken;<br>    }</pre><pre>    refreshTokenIfNeeded();<br>    TokenState refreshed = tokenState;<br>    if (refreshed != null &amp;&amp; StringUtils.isNotBlank(refreshed.accessToken)) {<br>        return refreshed.accessToken;<br>    }</pre><pre>    throw new IOException(&quot;Unable to retrieve a valid access token&quot;);<br>}</pre><h3>Step 6: Locking, With a Timeout and a Failure Cooldown</h3><p>This is the step where most sample implementations quietly introduce a production risk: an unbounded lock() call. If the token endpoint hangs — a slow network, a misbehaving auth server — every thread waiting on that lock blocks <strong>indefinitely</strong>, and under load that can exhaust your servlet thread pool.</p><p>The fix is a bounded tryLock plus a short cooldown after a failed refresh, so a broken token endpoint doesn&#39;t turn into a self-inflicted denial-of-service against your own AEM instance:</p><pre>private void refreshTokenIfNeeded() throws IOException {<br>    TokenState current = tokenState;<br>    if (isTokenUsable(current, oauthEarlyRefreshWindowSeconds)) {<br>        return;<br>    }</pre><pre>    if (System.currentTimeMillis() - lastFailureAt &lt; oauthFailureCooldownSeconds * 1000L) {<br>        // A refresh failed very recently — avoid hammering a struggling token endpoint.<br>        // Fall through and let the caller work with whatever state exists (or fail fast).<br>        return;<br>    }</pre><pre>    boolean locked = false;<br>    try {<br>        locked = tokenLock.tryLock(oauthRefreshLockTimeoutSeconds, TimeUnit.SECONDS);<br>        if (!locked) {<br>            LOG.warn(&quot;Timed out waiting for token refresh lock after {}s&quot;, oauthRefreshLockTimeoutSeconds);<br>            return;<br>        }</pre><pre>        current = tokenState;<br>        if (isTokenUsable(current, oauthEarlyRefreshWindowSeconds)) {<br>            return;<br>        }</pre><pre>        try {<br>            TokenState refreshed = fetchToken(oauthClientId, oauthClientSecret, oauthTokenUrl);<br>            tokenState = refreshed;<br>            lastFailureAt = 0L;<br>        } catch (IOException e) {<br>            lastFailureAt = System.currentTimeMillis();<br>            throw e;<br>        }<br>    } catch (InterruptedException e) {<br>        Thread.currentThread().interrupt();<br>        throw new IOException(&quot;Interrupted while waiting for token refresh lock&quot;, e);<br>    } finally {<br>        if (locked) {<br>            tokenLock.unlock();<br>        }<br>    }<br>}</pre><p>What this buys you over a plain lock():</p><ul><li><strong>Bounded wait.</strong> A stuck token endpoint degrades one request path instead of wedging a thread pool.</li><li><strong>Failure cooldown.</strong> If the token endpoint is down, you get one attempt every oauthFailureCooldownSeconds, not one attempt per incoming request.</li></ul><h3>Step 7: Define Token Usability With an Early Refresh Window</h3><p>Never use a token right up to its exact expiry — clock drift and in-flight requests will cause boundary failures.</p><pre>private boolean isTokenUsable(TokenState state, int earlyRefreshWindowSeconds) {<br>    if (state == null || StringUtils.isBlank(state.accessToken)) {<br>        return false;<br>    }</pre><pre>    long earlyRefreshWindow = Math.max(0, earlyRefreshWindowSeconds) * 1000L;<br>    return System.currentTimeMillis() &lt; state.expiresAt - earlyRefreshWindow;<br>}</pre><p>Example: if expiresAt is 10:30:00 and the early window is 120 seconds, refresh is forced starting at 10:28:00 — not at the wire.</p><h3>Step 8: Fetch and Parse the Token Response</h3><pre>private TokenState fetchToken(String clientId, String clientSecret, String tokenUrl) throws IOException {<br>    String responseBody = tokenService.getToken(clientId, clientSecret, tokenUrl);</pre><pre>    JsonNode rootNode = OBJECT_MAPPER.readTree(responseBody);<br>    String accessToken = rootNode.path(&quot;access_token&quot;).asText(null);<br>    int expiresIn = rootNode.path(&quot;expires_in&quot;).asInt(1800);</pre><pre>    if (StringUtils.isBlank(accessToken)) {<br>        throw new IOException(&quot;access_token missing in token API response&quot;);<br>    }<br>    if (expiresIn &lt;= 0) {<br>        expiresIn = 1800;<br>    }</pre><pre>    long issuedAt = System.currentTimeMillis();<br>    long expiresAt = issuedAt + (expiresIn * 1000L);<br>    return new TokenState(accessToken, issuedAt, expiresAt);<br>}</pre><p>The tokenService.getToken(...) call inside this method should have its <strong>own connect and read timeouts</strong> at the HTTP client level. The lock timeout in Step 6 protects other threads from waiting too long; it doesn&#39;t stop the refreshing thread itself from hanging forever inside a client with no timeout configured.</p><h3>Step 9: Implement invalidateToken</h3><pre>@Override<br>public void invalidateToken() {<br>    tokenLock.lock();<br>    try {<br>        tokenState = null;<br>    } finally {<br>        tokenLock.unlock();<br>    }<br>}</pre><p><strong>A note on ordering:</strong> invalidateToken() and a concurrent successful refreshTokenIfNeeded() both write to tokenState under the same lock, so they can&#39;t interleave with each other — but if invalidation is triggered by a slow, now-stale 401 response that arrives <em>after</em> another thread has already refreshed the token, the invalidate can still clobber a perfectly good, freshly-issued token. In practice this only costs you one extra refresh on the next call, not correctness, so it&#39;s usually fine to accept. If you want to close it entirely, have invalidateToken() only clear the state if it matches the token snapshot the caller actually saw fail (compare-and-clear), rather than clearing unconditionally.</p><h3>Step 10: One-Time Retry on 401/403</h3><pre>@Override<br>public HttpServiceResponse executeWithFreshTokenRetry(TokenRequestExecutor requestExecutor) throws IOException {<br>    HttpServiceResponse response = requestExecutor.execute(getValidAccessToken());</pre><pre>    if (response != null &amp;&amp; (response.getStatusCode() == 401 || response.getStatusCode() == 403)) {<br>        invalidateToken();<br>        response = requestExecutor.execute(getValidAccessToken());<br>    }<br>    return response;<br>}</pre><p>Retry <strong>exactly once</strong> — never loop.</p><blockquote><strong><em>Caveat:</em></strong><em> this assumes your HTTP client returns a response object with a status code on 401/403 rather than throwing an exception. Some clients (and some HttpClient wrapper libraries) throw on any non-2xx status. If yours does, catch the specific exception type for 401/403 around both calls and rethrow anything else, rather than branching on </em><em>getStatusCode().</em></blockquote><h3>Step 11: Use the Service From Any Backend Caller</h3><pre>@Component(service = ExampleBackendService.class)<br>public class ExampleBackendService {</pre><pre>    @Reference<br>    private TokenAuthService tokenAuthService;</pre><pre>    @Reference<br>    private BackendHttpService backendHttpService;</pre><pre>    public HttpServiceResponse fetchProfile(String userId) throws IOException {<br>        return tokenAuthService.executeWithFreshTokenRetry(accessToken -&gt;<br>            backendHttpService.get(<br>                &quot;/profiles/&quot; + userId,<br>                Map.of(<br>                    &quot;Authorization&quot;, &quot;Bearer &quot; + accessToken,<br>                    &quot;X-Correlation-Id&quot;, UUID.randomUUID().toString(),<br>                    &quot;X-Client-Channel&quot;, &quot;aem-backend&quot;<br>                )<br>            )<br>        );<br>    }<br>}</pre><p>If a single AEM request makes multiple backend calls, every one of them can go through this same shared service safely — that’s the entire point of centralizing it.</p><h3>A Note on WAF and Auth Gateways</h3><p>Many AEM deployments sit behind a WAF or policy-enforcement layer in front of the backend. A few things to keep in mind there:</p><ul><li>Keep the token endpoint and resource endpoint hostnames in whatever allowlist your WAF requires.</li><li>Make sure AEM’s outbound egress IPs are allowed if the WAF does source filtering.</li><li>Send whatever routing/observability headers the WAF expects, and avoid duplicate Authorization headers.</li><li>Treat 401 and 403 from the WAF the same way you treat them from the backend itself: invalidate and retry once.</li><li>If the WAF can also return something like a 429 or a custom deny code, handle that in your HTTP client layer — it isn’t a token problem and retrying with a fresh token won’t fix it.</li></ul><h3>Step 12: Startup Warm-Up (Optional)</h3><pre>private void warmUpTokenCache() {<br>    try {<br>        getValidAccessToken();<br>    } catch (IOException e) {<br>        LOG.warn(&quot;Startup token warm-up failed; request path will retry&quot;, e);<br>    }<br>}</pre><p>A failed warm-up should never fail component activation — it just means the first real request pays the refresh cost instead.</p><h3>Logging and Security Rules</h3><p>Log:</p><ul><li>Token refresh start/completion and elapsed time.</li><li>Retry-on-401/403 counts.</li><li>Time remaining until expiry at the point of use.</li></ul><p>Never log the full secret or token value:</p><pre>private String maskForLog(String value) {<br>    if (StringUtils.isBlank(value)) {<br>        return &quot;&lt;blank&gt;&quot;;<br>    }<br>    int len = value.length();<br>    if (len &lt;= 8) {<br>        return &quot;****&quot;;<br>    }<br>    return value.substring(0, 4) + &quot;...&quot; + value.substring(len - 4);<br>}</pre><h3>Production Checklist</h3><ol><li>OAuth config validated before use.</li><li>Shared token state is an immutable snapshot.</li><li>Shared token reference is volatile.</li><li>Refresh path protected by a <strong>bounded</strong> lock (tryLock + timeout), not a plain lock().</li><li>Failed refreshes are rate-limited with a short cooldown.</li><li>Early-refresh window configured, not zero.</li><li>@Modified clears cached state on config change (e.g., secret rotation).</li><li>Retry exactly once on 401/403 — never in a loop.</li><li>Token endpoint calls have explicit connect/read timeouts.</li><li>Secrets and tokens masked in logs, never logged raw.</li><li>Metrics for refresh frequency, refresh failures, and lock timeouts.</li></ol><h3>Common Mistakes</h3><ol><li>Generating a new token on every servlet call.</li><li>Using synchronized (or a plain lock()) for the entire read/write path, including normal reads.</li><li>No early-refresh window, causing boundary failures right at expiry.</li><li>Infinite retry loop on 401.</li><li>No timeout on the refresh lock, so a hung token endpoint exhausts the thread pool.</li><li>Logging raw token or secret values.</li></ol><h3>Summary</h3><p>For AEM backend integrations, the reliable pattern is:</p><ol><li>Centralize token management in one OSGi service.</li><li>Cache the token in memory as an immutable snapshot.</li><li>Refresh only when needed, behind a bounded lock with a failure cooldown.</li><li>Reuse the token across every backend call in a request.</li><li>Retry exactly once, with a fresh token, on auth failure.</li></ol><p>Get those five things right and the token layer disappears into the background — which is exactly where you want it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae5c3cbf2310" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>