Skip to content

fix(sso): share one MSAL4J application so Entra ID silent refresh can work - #3227

Open
marevol wants to merge 1 commit into
masterfrom
entraid-shared-client-application
Open

fix(sso): share one MSAL4J application so Entra ID silent refresh can work#3227
marevol wants to merge 1 commit into
masterfrom
entraid-shared-client-application

Conversation

@marevol

@marevol marevol commented Aug 9, 2026

Copy link
Copy Markdown
Contributor

Problem

getAccessToken() (both overloads) and refreshTokenSilently() each built their own client
application:

final ConfidentialClientApplication app = ConfidentialClientApplication
        .builder(getClientId(), ClientCredentialFactory.createFromSecret(getClientSecret()))
        .authority(authority)
        .build();

Every ConfidentialClientApplication owns its own in-memory TokenCache
(AbstractClientApplicationBase: super.tokenCache = new TokenCache(builder.tokenCacheAccessAspect)),
and no ITokenCacheAccessAspect is configured, so nothing persists it. msal4j's
AcquireTokenSilentSupplier then does:

res = clientApplication.tokenCache.getCachedAuthenticationResult(account, requestAuthority, scopes, clientId);
if (res == null) {
    throw new MsalClientException(AuthenticationErrorMessage.NO_TOKEN_IN_CACHE, AuthenticationErrorCode.CACHE_MISS);
}

The tokens acquired at login went into an instance discarded immediately afterwards, so
acquireTokenSilently looked in an empty cache every time. refreshTokenSilently() always
threw, always returned null, and EntraIdCredential.refresh() never took its success branch:

final IAuthenticationResult newResult = authenticator.refreshTokenSilently(this);
if (newResult != null) {        // never
    authResult = newResult;
    authenticator.updateMemberOf(this);
    ...
}

So updateMemberOf() never ran again after login. A user's groups and roles were whatever they
had been at login for the whole life of the session, no matter what changed in Entra ID.

Fix

Hold one application per authenticator — which is what msal4j documents as the intended usage,
and what keeps the token cache alive between the login and its refresh.

getClientApplication() rebuilds it when the client id, secret or tenant changes, because all
three are editable from the admin screen while Fess is running. The build is double-checked under
a lock so concurrent logins share one cache rather than racing to create two. The cache key
reduces the secret to a hash so it cannot travel into a log line or a heap dump label.

Also drops a now-unused local in refreshTokenSilently().

What this deliberately does not change

When a refresh genuinely fails, refresh() still returns false and
FessBaseAction.godHandPrologue still discards that value:

final boolean result = u.getFessUser().refresh();
if (logger.isDebugEnabled()) { logger.debug("Refreshed user info: result={}", result); }

Acting on it would log the user out, and it would affect every FessUser implementation — LDAP,
OpenID Connect, SAML — not just Entra ID. That belongs in its own change.

Note also that the cache is in-memory: it does not survive a restart, and it is not shared across
a cluster. In both cases the behaviour degrades to what it is today (the refresh fails, the
session keeps its existing token until it expires), not to something worse.

Tests

EntraIdAuthenticator's unit test class, 3 new tests:

  • test_getClientApplication_isReusedSoItsTokenCacheSurvives
  • test_getClientApplication_isRebuiltWhenTheConfigurationChanges — secret, client id and tenant
    each independently
  • test_getClientApplication_isBuiltOnceUnderConcurrentAccess — 8 threads must share one instance

Falsification: with the reuse check removed so the application is rebuilt every call, the first
and third fail.

The end-to-end refresh — login, wait for expiry, silent re-acquisition — needs a real tenant and
is not covered here. What is covered is the mechanism that made it impossible.

Tests run: 134, Failures: 0, Errors: 0, Skipped: 0

(the whole org.codelibs.fess.sso package)

… work

getAccessToken() and refreshTokenSilently() each built their own
ConfidentialClientApplication. Every instance owns its own in-memory TokenCache,
and msal4j's AcquireTokenSilentSupplier throws
MsalClientException(NO_TOKEN_IN_CACHE, CACHE_MISS) when the account is not in it:

    res = clientApplication.tokenCache.getCachedAuthenticationResult(account, ...);
    if (res == null) {
        throw new MsalClientException(AuthenticationErrorMessage.NO_TOKEN_IN_CACHE, ...);
    }

The tokens acquired at login therefore went into an instance that was discarded
immediately afterwards, and acquireTokenSilently could never find them.
refreshTokenSilently() always threw, always returned null, and
EntraIdCredential.refresh() never took its success branch -- so updateMemberOf()
never ran again for the life of the session and a user's group membership was
whatever it had been at login.

Hold one application per authenticator, which is what msal4j documents as the
intended usage, and rebuild it when the client id, secret or tenant changes,
since all three are editable from the admin screen while Fess is running. The
build is double-checked so concurrent logins share one token cache.

This does not change what happens when a refresh genuinely fails:
refresh() still returns false and FessBaseAction still ignores that. Acting on
it would affect every FessUser implementation, not just Entra ID.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant