This is an automated email from the ASF dual-hosted git repository.

ffang pushed a commit to branch 4.1.x-fixes
in repository https://gitbox.apache.org/repos/asf/cxf.git


The following commit(s) were added to refs/heads/4.1.x-fixes by this push:
     new 362e55f8d53 CXF-9259: Respect shared JCache ownership and replay entry 
expiry (#3752)
362e55f8d53 is described below

commit 362e55f8d5370a5621920b4a80f429543f0f4168
Author: Freeman(Yue) Fang <[email protected]>
AuthorDate: Wed Nov 25 09:07:05 2026 -0500

    CXF-9259: Respect shared JCache ownership and replay entry expiry (#3752)
    
    * CXF-9259: Respect shared JCache ownership and replay entry expiry
    
    Reference-count the caches and cache managers that WS-Security, the JAX-RS 
token replay cache (which SAML SSO and the OAuth2 SAML bearer validator use), 
SAML SSO state, and OAuth2 obtain. Release each owner independently and 
preserve externally owned caches. Destroy a CXF-created cache when its last 
user releases it, and close a manager obtained for a CXF configuration URI when 
its last user releases it, so that its resources, such as a disk store lock, 
are freed for a redeployed appl [...]
    
    Enforce replay identifiers' absolute expiry through atomic entry 
processors. With Ehcache, evict each identifier at its own expiry, including 
when it is replaced; with other providers, bound the retention of identifiers 
that are not looked up again by the maximum replay-cache TTL. Give an expiry 
that is not in the future the default TTL, as EHCacheExpiry does. As 
identifiers are now held until their own expiry, report the maximum 
replay-cache TTL to WSS4J, so that a OneTimeUse asserti [...]
    
    * CXF-9259: Address review comments
    
    Use Ehcache's per-entry replay expiry only when the provider is the same 
copy of Ehcache that CXF sees, and fall back to a JCache configuration if 
building or using the Ehcache configuration fails, rather than failing to 
create the replay cache. Without it, hold every replay identifier for the 
default TTL, as before, rather than the max TTL, and report the default TTL to 
WSS4J. Report the max TTL only when the cache really evicts each identifier at 
its own expiry.
    
    Release the caches and manager that an OAuth2 data provider obtained when 
its construction fails, and keep the code grant cache reference after close, so 
that a request still in flight fails as on a closed cache rather than with a 
NullPointerException.
    
    Release the STS identity cache and the XKMS client cache through the shared 
ownership too: closing an XKMS client cache no longer closes the provider's 
default manager, which other caches such as the WS-Security replay caches use, 
and closing one STS identity cache no longer destroys the cache other instances 
share.
    
    Make the Ehcache eviction test independent of the machine's speed, and 
cover the expiry durations with a test clock.
    
    * CXF-9259: Release the replay cache if its construction fails
    
    Also document that every user of JCacheUtils must release what it obtained.
    
    (cherry picked from commit 27743d5c3d4e6d42a07645efb3d9b84544580fa2)
---
 .../oauth2/grants/code/JCacheCodeDataProvider.java |  17 +-
 .../oauth2/provider/JCacheOAuthDataProvider.java   |  67 +++---
 .../oauth2/grants/code/JCacheLifecycleTest.java    |  97 +++++++++
 .../sso/state/jcache/JCacheSPStateManager.java     |  42 ++--
 .../rs/security/saml/sso/JCacheLifecycleTest.java  |  91 ++++++++
 .../common/jcache/JCacheTokenReplayCache.java      |  43 ++--
 .../JCacheTokenReplayCacheLifecycleTest.java       |  76 +++++++
 rt/security/pom.xml                                |  15 ++
 .../apache/cxf/rt/security/utils/JCacheUtils.java  | 125 +++++++++++
 .../cxf/rt/security/utils/JCacheUtilsTest.java     | 114 ++++++++++
 .../src/test/resources/jcache-utils-test.xml       |  20 ++
 .../security/cache/jcache/EhcacheReplayExpiry.java |  95 +++++++++
 .../security/cache/jcache/JCacheReplayCache.java   | 181 ++++++++++++----
 .../tokenstore/jcache/JCacheTokenStore.java        |  23 ++-
 .../cxf/ws/security/utils/JCacheSupport.java       |  12 +-
 .../cache/jcache/JCacheReplayCacheTest.java        | 229 ++++++++++++++++++++-
 .../jcache/JCacheTokenStoreLifecycleTest.java      |  51 +++++
 .../cxf/sts/cache/jcache/JCacheIdentityCache.java  |  21 +-
 .../jcache/JCacheIdentityCacheLifecycleTest.java   |  53 +++++
 .../xkms/cache/jcache/JCacheXKMSClientCache.java   |  16 +-
 .../jcache/JCacheXKMSClientCacheLifecycleTest.java |  54 +++++
 21 files changed, 1294 insertions(+), 148 deletions(-)

diff --git 
a/rt/rs/security/oauth-parent/oauth2/src/main/java/org/apache/cxf/rs/security/oauth2/grants/code/JCacheCodeDataProvider.java
 
b/rt/rs/security/oauth-parent/oauth2/src/main/java/org/apache/cxf/rs/security/oauth2/grants/code/JCacheCodeDataProvider.java
index 80085e35be9..2477ed78827 100644
--- 
a/rt/rs/security/oauth-parent/oauth2/src/main/java/org/apache/cxf/rs/security/oauth2/grants/code/JCacheCodeDataProvider.java
+++ 
b/rt/rs/security/oauth-parent/oauth2/src/main/java/org/apache/cxf/rs/security/oauth2/grants/code/JCacheCodeDataProvider.java
@@ -33,6 +33,7 @@ import org.apache.cxf.rs.security.oauth2.common.UserSubject;
 import org.apache.cxf.rs.security.oauth2.provider.JCacheOAuthDataProvider;
 import org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException;
 import org.apache.cxf.rs.security.oauth2.utils.OAuthUtils;
+import org.apache.cxf.rt.security.utils.JCacheUtils;
 
 public class JCacheCodeDataProvider extends JCacheOAuthDataProvider
     implements AuthorizationCodeDataProvider {
@@ -40,6 +41,7 @@ public class JCacheCodeDataProvider extends 
JCacheOAuthDataProvider
 
     private long codeLifetime = 10 * 60;
     private Cache<String, ServerAuthorizationCodeGrant> grantCache;
+    private boolean grantCacheReleased;
 
     protected JCacheCodeDataProvider() {
         this(DEFAULT_CONFIG_URL, BusFactory.getThreadDefaultBus(true));
@@ -67,7 +69,12 @@ public class JCacheCodeDataProvider extends 
JCacheOAuthDataProvider
                                      String refreshTokenKey,
                                      boolean storeJwtTokenKeyOnly) {
         super(configFileURL, bus, clientCacheKey, accessTokenKey, 
refreshTokenKey, storeJwtTokenKeyOnly);
-        grantCache = createCache(cacheManager, codeCacheKey, String.class, 
ServerAuthorizationCodeGrant.class);
+        try {
+            grantCache = createCache(cacheManager, codeCacheKey, String.class, 
ServerAuthorizationCodeGrant.class);
+        } catch (RuntimeException ex) {
+            super.close();
+            throw ex;
+        }
     }
 
 
@@ -138,8 +145,12 @@ public class JCacheCodeDataProvider extends 
JCacheOAuthDataProvider
     }
 
     @Override
-    public void close() {
-        grantCache.close();
+    public synchronized void close() {
+        // keep the reference, so that a request still in flight fails as on a 
closed cache, not with an NPE
+        if (!grantCacheReleased) {
+            grantCacheReleased = true;
+            JCacheUtils.release(grantCache);
+        }
         super.close();
     }
 }
diff --git 
a/rt/rs/security/oauth-parent/oauth2/src/main/java/org/apache/cxf/rs/security/oauth2/provider/JCacheOAuthDataProvider.java
 
b/rt/rs/security/oauth-parent/oauth2/src/main/java/org/apache/cxf/rs/security/oauth2/provider/JCacheOAuthDataProvider.java
index c3e63c3c38a..7126a9e9aa1 100644
--- 
a/rt/rs/security/oauth-parent/oauth2/src/main/java/org/apache/cxf/rs/security/oauth2/provider/JCacheOAuthDataProvider.java
+++ 
b/rt/rs/security/oauth-parent/oauth2/src/main/java/org/apache/cxf/rs/security/oauth2/provider/JCacheOAuthDataProvider.java
@@ -28,7 +28,6 @@ import java.util.Set;
 import javax.cache.Cache;
 import javax.cache.CacheManager;
 import javax.cache.Caching;
-import javax.cache.configuration.MutableConfiguration;
 import javax.cache.spi.CachingProvider;
 
 import org.apache.cxf.Bus;
@@ -40,6 +39,7 @@ import org.apache.cxf.rs.security.oauth2.common.UserSubject;
 import org.apache.cxf.rs.security.oauth2.tokens.refresh.RefreshToken;
 import org.apache.cxf.rs.security.oauth2.utils.JwtTokenUtils;
 import org.apache.cxf.rs.security.oauth2.utils.OAuthUtils;
+import org.apache.cxf.rt.security.utils.JCacheUtils;
 
 import static org.apache.cxf.jaxrs.utils.ResourceUtils.getClasspathResourceURL;
 
@@ -55,6 +55,7 @@ public class JCacheOAuthDataProvider extends 
AbstractOAuthDataProvider {
     private Cache<String, String> jwtAccessTokenCache;
     private final Cache<String, RefreshToken> refreshTokenCache;
     private boolean storeJwtTokenKeyOnly;
+    private boolean closed;
     private JoseJwtConsumer jwtTokenConsumer;
 
     public JCacheOAuthDataProvider() {
@@ -88,16 +89,26 @@ public class JCacheOAuthDataProvider extends 
AbstractOAuthDataProvider {
                                    boolean storeJwtTokenKeyOnly) {
 
         cacheManager = createCacheManager(configFileURL, bus);
-        clientCache = createCache(cacheManager, clientCacheKey, String.class, 
Client.class);
-
         this.storeJwtTokenKeyOnly = storeJwtTokenKeyOnly;
-        if (storeJwtTokenKeyOnly) {
-            jwtAccessTokenCache = createCache(cacheManager, 
accessTokenCacheKey, String.class, String.class);
-        } else {
-            accessTokenCache = createCache(cacheManager, accessTokenCacheKey, 
String.class, ServerAccessToken.class);
+        Cache<String, Client> clients = null;
+        Cache<String, RefreshToken> refreshTokens = null;
+        try {
+            clients = createCache(cacheManager, clientCacheKey, String.class, 
Client.class);
+            if (storeJwtTokenKeyOnly) {
+                jwtAccessTokenCache = createCache(cacheManager, 
accessTokenCacheKey, String.class, String.class);
+            } else {
+                accessTokenCache = createCache(cacheManager, 
accessTokenCacheKey, String.class,
+                                               ServerAccessToken.class);
+            }
+            refreshTokens = createCache(cacheManager, refreshTokenCacheKey, 
String.class, RefreshToken.class);
+        } catch (RuntimeException ex) {
+            // release what was obtained, so that the manager (and its disk 
store) is not kept open
+            releaseAll(clients, accessTokenCache, jwtAccessTokenCache, null);
+            JCacheUtils.releaseCacheManager(cacheManager);
+            throw ex;
         }
-
-        refreshTokenCache = createCache(cacheManager, refreshTokenCacheKey, 
String.class, RefreshToken.class);
+        clientCache = clients;
+        refreshTokenCache = refreshTokens;
     }
 
     @Override
@@ -193,16 +204,21 @@ public class JCacheOAuthDataProvider extends 
AbstractOAuthDataProvider {
     }
 
     @Override
-    public void close() {
+    public synchronized void close() {
+        if (closed) {
+            return;
+        }
+        closed = true;
+        releaseAll(clientCache, accessTokenCache, jwtAccessTokenCache, 
refreshTokenCache);
+        JCacheUtils.releaseCacheManager(cacheManager);
+    }
 
-        clientCache.close();
-        refreshTokenCache.close();
-        if (accessTokenCache != null) {
-            accessTokenCache.close();
-        } else {
-            jwtAccessTokenCache.close();
+    private static void releaseAll(Cache<?, ?>... caches) {
+        for (Cache<?, ?> cache : caches) {
+            if (cache != null) {
+                JCacheUtils.release(cache);
+            }
         }
-        cacheManager.close();
     }
 
     protected static <V extends ServerAccessToken> V getToken(Cache<String, V> 
cache, String key) {
@@ -278,6 +294,7 @@ public class JCacheOAuthDataProvider extends 
AbstractOAuthDataProvider {
         return OAuthUtils.isExpired(token.getIssuedAt(), token.getExpiresIn());
     }
 
+    /** The manager is released with JCacheUtils.releaseCacheManager, which 
close() does. */
     protected static CacheManager createCacheManager(String configFile, Bus 
bus) {
         if (bus == null) {
             bus = BusFactory.getThreadDefaultBus(true);
@@ -294,24 +311,14 @@ public class JCacheOAuthDataProvider extends 
AbstractOAuthDataProvider {
             configFileURI = provider.getDefaultURI();
         }
 
-        return provider.getCacheManager(configFileURI, 
Thread.currentThread().getContextClassLoader());
+        return JCacheUtils.getCacheManager(provider, configFileURI, 
Thread.currentThread().getContextClassLoader());
     }
 
     protected static <K, V> Cache<K, V> createCache(CacheManager cacheManager,
                                                     String cacheKey, Class<K> 
keyType, Class<V> valueType) {
 
-        Cache<K, V> cache = cacheManager.getCache(cacheKey, keyType, 
valueType);
-        if (cache == null) {
-            cache = cacheManager.createCache(
-                cacheKey,
-                new MutableConfiguration<K, V>()
-                    .setTypes(keyType, valueType)
-                    .setStoreByValue(true)
-                    .setStatisticsEnabled(false)
-            );
-        }
-
-        return cache;
+        return JCacheUtils.getOrCreate(cacheManager, cacheKey, keyType, 
valueType,
+            configuration -> 
configuration.setStoreByValue(true).setStatisticsEnabled(false));
     }
 
     public boolean isStoreJwtTokenKeyOnly() {
diff --git 
a/rt/rs/security/oauth-parent/oauth2/src/test/java/org/apache/cxf/rs/security/oauth2/grants/code/JCacheLifecycleTest.java
 
b/rt/rs/security/oauth-parent/oauth2/src/test/java/org/apache/cxf/rs/security/oauth2/grants/code/JCacheLifecycleTest.java
new file mode 100644
index 00000000000..88452d2f2e4
--- /dev/null
+++ 
b/rt/rs/security/oauth-parent/oauth2/src/test/java/org/apache/cxf/rs/security/oauth2/grants/code/JCacheLifecycleTest.java
@@ -0,0 +1,97 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.cxf.rs.security.oauth2.grants.code;
+
+import java.net.URI;
+
+import javax.cache.CacheManager;
+import javax.cache.Caching;
+import javax.cache.configuration.MutableConfiguration;
+
+import org.apache.cxf.rs.security.oauth2.common.Client;
+import org.apache.cxf.rs.security.oauth2.provider.JCacheOAuthDataProvider;
+
+import org.junit.Test;
+
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertThrows;
+import static org.junit.Assert.assertTrue;
+
+public class JCacheLifecycleTest {
+    private static final String CONFIG = "cxf-oauth2-jcache.xml";
+
+    @Test
+    public void testSharedCodeAndOAuthProvidersSurviveClose() {
+        JCacheCodeDataProvider first = new JCacheCodeDataProvider();
+        JCacheCodeDataProvider same = new JCacheCodeDataProvider();
+        JCacheOAuthDataProvider oauth = new JCacheOAuthDataProvider();
+        try {
+            Client client = new Client("shared-client", "secret", true);
+            first.setClient(client);
+            AuthorizationCodeRegistration registration = new 
AuthorizationCodeRegistration();
+            registration.setClient(client);
+            ServerAuthorizationCodeGrant grant = 
first.createCodeGrant(registration);
+            first.close();
+            first.close();
+            assertNotNull(same.getClient("shared-client"));
+            assertNotNull(same.getCodeGrant(grant.getCode()));
+            assertNotNull(oauth.getClient("shared-client"));
+            same.close();
+            assertNotNull(oauth.getClient("shared-client"));
+        } finally {
+            first.close();
+            same.close();
+            oauth.close();
+        }
+    }
+
+    /**
+     * A constructor that fails after obtaining the manager of a configuration 
file releases it, so that it
+     * is closed (and its disk store unlocked) rather than kept open.
+     */
+    @Test
+    public void testFailedConstructionReleasesManager() throws Exception {
+        CacheManager manager = conflictingCache("lifecycle-refresh");
+        assertThrows(RuntimeException.class, () -> new 
JCacheOAuthDataProvider(CONFIG, null,
+            "lifecycle-client", "lifecycle-access", "lifecycle-refresh"));
+        assertTrue(manager.isClosed());
+
+        manager = conflictingCache("lifecycle-code");
+        assertThrows(RuntimeException.class, () -> new 
JCacheCodeDataProvider(CONFIG, null,
+            "lifecycle-client", "lifecycle-code", "lifecycle-access", 
"lifecycle-refresh"));
+        assertTrue(manager.isClosed());
+    }
+
+    // A request still in flight after close fails as on a closed cache, not 
with a NullPointerException
+    @Test
+    public void testUseAfterClose() {
+        JCacheCodeDataProvider provider = new JCacheCodeDataProvider();
+        provider.close();
+        assertThrows(IllegalStateException.class, () -> 
provider.getCodeGrant("code"));
+    }
+
+    // a cache of the given name, with other types than the providers use, in 
their configuration's manager
+    private static CacheManager conflictingCache(String name) throws Exception 
{
+        URI uri = JCacheLifecycleTest.class.getResource("/" + CONFIG).toURI();
+        CacheManager manager = Caching.getCachingProviders().iterator().next()
+            .getCacheManager(uri, 
Thread.currentThread().getContextClassLoader());
+        manager.createCache(name, new MutableConfiguration<Integer, 
Integer>().setTypes(Integer.class, Integer.class));
+        return manager;
+    }
+}
diff --git 
a/rt/rs/security/sso/saml/src/main/java/org/apache/cxf/rs/security/saml/sso/state/jcache/JCacheSPStateManager.java
 
b/rt/rs/security/sso/saml/src/main/java/org/apache/cxf/rs/security/saml/sso/state/jcache/JCacheSPStateManager.java
index 4932a5d0dd9..4de36c05c85 100644
--- 
a/rt/rs/security/sso/saml/src/main/java/org/apache/cxf/rs/security/saml/sso/state/jcache/JCacheSPStateManager.java
+++ 
b/rt/rs/security/sso/saml/src/main/java/org/apache/cxf/rs/security/saml/sso/state/jcache/JCacheSPStateManager.java
@@ -25,7 +25,6 @@ import java.net.URL;
 import javax.cache.Cache;
 import javax.cache.CacheManager;
 import javax.cache.Caching;
-import javax.cache.configuration.MutableConfiguration;
 import javax.cache.spi.CachingProvider;
 
 import org.apache.cxf.Bus;
@@ -34,6 +33,7 @@ import org.apache.cxf.jaxrs.utils.ResourceUtils;
 import org.apache.cxf.rs.security.saml.sso.state.RequestState;
 import org.apache.cxf.rs.security.saml.sso.state.ResponseState;
 import org.apache.cxf.rs.security.saml.sso.state.SPStateManager;
+import org.apache.cxf.rt.security.utils.JCacheUtils;
 import org.apache.wss4j.common.util.Loader;
 
 /**
@@ -51,6 +51,7 @@ public class JCacheSPStateManager implements SPStateManager {
     private final Cache<String, RequestState> requestCache;
     private final Cache<String, ResponseState> responseCache;
     private final CacheManager cacheManager;
+    private boolean closed;
 
     public JCacheSPStateManager() throws URISyntaxException {
         this(DEFAULT_CONFIG_URL, null);
@@ -79,26 +80,28 @@ public class JCacheSPStateManager implements SPStateManager 
{
 
         final CachingProvider cachingProvider = Caching.getCachingProvider();
 
-        cacheManager = cachingProvider.getCacheManager(
-            getConfigFileURL(configFileURL).toURI(), 
-            getClass().getClassLoader()); 
+        cacheManager = JCacheUtils.getCacheManager(cachingProvider,
+            getConfigFileURL(configFileURL).toURI(),
+            getClass().getClassLoader());
 
-        requestCache = getOrCreate(cacheManager, REQUEST_CACHE_KEY, 
String.class, RequestState.class);
-        responseCache = getOrCreate(cacheManager, RESPONSE_CACHE_KEY, 
String.class, ResponseState.class);
+        Cache<String, RequestState> request = null;
+        try {
+            request = getOrCreate(cacheManager, REQUEST_CACHE_KEY, 
String.class, RequestState.class);
+            responseCache = getOrCreate(cacheManager, RESPONSE_CACHE_KEY, 
String.class, ResponseState.class);
+        } catch (RuntimeException ex) {
+            if (request != null) {
+                JCacheUtils.release(request);
+            }
+            JCacheUtils.releaseCacheManager(cacheManager);
+            throw ex;
+        }
+        requestCache = request;
     }
 
     private static <K, V> Cache<K, V> getOrCreate(CacheManager cacheManager, 
String name,
             Class<K> kclass, Class<V> vclass) {
 
-        final Cache<K, V> cache = cacheManager.getCache(name, kclass, vclass);
-        if (cache != null) {
-            return cache;
-        }
-
-        final MutableConfiguration<K, V> cacheConfiguration = new 
MutableConfiguration<>();
-        cacheConfiguration.setTypes(kclass, vclass);
-
-        return cacheManager.createCache(name, cacheConfiguration);
+        return JCacheUtils.getOrCreate(cacheManager, name, kclass, vclass);
     }
 
     private URL getConfigFileURL(URL suppliedConfigFileURL) {
@@ -155,10 +158,11 @@ public class JCacheSPStateManager implements 
SPStateManager {
     }
 
     public synchronized void close() throws IOException {
-        if (!cacheManager.isClosed()) {
-            cacheManager.destroyCache(REQUEST_CACHE_KEY);
-            cacheManager.destroyCache(RESPONSE_CACHE_KEY);
-            cacheManager.close();
+        if (!closed) {
+            closed = true;
+            JCacheUtils.release(requestCache);
+            JCacheUtils.release(responseCache);
+            JCacheUtils.releaseCacheManager(cacheManager);
         }
     }
 
diff --git 
a/rt/rs/security/sso/saml/src/test/java/org/apache/cxf/rs/security/saml/sso/JCacheLifecycleTest.java
 
b/rt/rs/security/sso/saml/src/test/java/org/apache/cxf/rs/security/saml/sso/JCacheLifecycleTest.java
new file mode 100644
index 00000000000..098c6f2c3d4
--- /dev/null
+++ 
b/rt/rs/security/sso/saml/src/test/java/org/apache/cxf/rs/security/saml/sso/JCacheLifecycleTest.java
@@ -0,0 +1,91 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.cxf.rs.security.saml.sso;
+
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.time.Instant;
+
+import javax.cache.Cache;
+import javax.cache.CacheManager;
+import javax.cache.Caching;
+import javax.cache.configuration.MutableConfiguration;
+
+import org.apache.cxf.rs.security.saml.sso.jcache.JCacheTokenReplayCache;
+import org.apache.cxf.rs.security.saml.sso.state.ResponseState;
+import org.apache.cxf.rs.security.saml.sso.state.jcache.JCacheSPStateManager;
+import org.apache.wss4j.common.cache.EHCacheValue;
+
+import org.junit.Test;
+
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+public class JCacheLifecycleTest {
+    @Test
+    public void testReplayAndStateCachesSurviveOtherUsersClosing() throws 
Exception {
+        JCacheTokenReplayCache replay = new JCacheTokenReplayCache();
+        JCacheTokenReplayCache sameReplay = new JCacheTokenReplayCache();
+        JCacheSPStateManager state = new JCacheSPStateManager();
+        JCacheSPStateManager sameState = new JCacheSPStateManager();
+        try {
+            replay.putId("retained");
+            state.setResponseState("context", new ResponseState("assertion", 
null, "/", null,
+                System.currentTimeMillis(), System.currentTimeMillis() + 
300000));
+            replay.close();
+            replay.close();
+            assertTrue(sameReplay.contains("retained"));
+            assertNotNull(state.getResponseState("context"));
+            state.close();
+            state.close();
+            assertNotNull(sameState.getResponseState("context"));
+            assertTrue(sameReplay.contains("retained"));
+        } finally {
+            replay.close();
+            sameReplay.close();
+            state.close();
+            sameState.close();
+        }
+    }
+
+    /**
+     * Closing the last user closes the manager of the configuration file, 
which releases its disk
+     * store, so that a redeployed application (another class loader) can 
create it again.
+     */
+    @Test
+    public void testLastCloseReleasesConfiguredManager() throws Exception {
+        JCacheTokenReplayCache replay = new JCacheTokenReplayCache();
+        JCacheSPStateManager state = new JCacheSPStateManager();
+        replay.putId("first");
+        replay.close();
+        state.close();
+
+        URL config = 
JCacheTokenReplayCache.class.getResource("/cxf-samlp-jcache.xml");
+        ClassLoader redeployed = new URLClassLoader(new URL[0], 
JCacheTokenReplayCache.class.getClassLoader());
+        CacheManager manager = 
Caching.getCachingProvider().getCacheManager(config.toURI(), redeployed);
+        try {
+            Cache<String, EHCacheValue> cache = 
manager.createCache("cxf.samlp.replay.cache",
+                new MutableConfiguration<String, 
EHCacheValue>().setTypes(String.class, EHCacheValue.class));
+            cache.put("second", new EHCacheValue("second", 
Instant.now().plusSeconds(60)));
+            assertTrue(cache.containsKey("second"));
+        } finally {
+            manager.close();
+        }
+    }
+}
diff --git 
a/rt/rs/security/xml/src/main/java/org/apache/cxf/rs/security/common/jcache/JCacheTokenReplayCache.java
 
b/rt/rs/security/xml/src/main/java/org/apache/cxf/rs/security/common/jcache/JCacheTokenReplayCache.java
index 063391b964c..9016bdfaa5c 100644
--- 
a/rt/rs/security/xml/src/main/java/org/apache/cxf/rs/security/common/jcache/JCacheTokenReplayCache.java
+++ 
b/rt/rs/security/xml/src/main/java/org/apache/cxf/rs/security/common/jcache/JCacheTokenReplayCache.java
@@ -34,7 +34,6 @@ import javax.cache.Cache;
 import javax.cache.CacheManager;
 import javax.cache.Caching;
 import javax.cache.configuration.CompleteConfiguration;
-import javax.cache.configuration.MutableConfiguration;
 import javax.cache.expiry.CreatedExpiryPolicy;
 import javax.cache.expiry.ExpiryPolicy;
 import javax.cache.spi.CachingProvider;
@@ -44,6 +43,7 @@ import org.apache.cxf.BusFactory;
 import org.apache.cxf.common.logging.LogUtils;
 import org.apache.cxf.jaxrs.utils.ResourceUtils;
 import org.apache.cxf.rs.security.common.TokenReplayCache;
+import org.apache.cxf.rt.security.utils.JCacheUtils;
 import org.apache.wss4j.common.cache.EHCacheExpiry;
 import org.apache.wss4j.common.cache.EHCacheValue;
 import org.apache.wss4j.common.util.Loader;
@@ -61,10 +61,10 @@ public class JCacheTokenReplayCache implements 
TokenReplayCache<String> {
     private static final Logger LOG = 
LogUtils.getL7dLogger(JCacheTokenReplayCache.class);
     private static final String DEFAULT_CONFIG_URL = 
"/cxf-rs-security-replay-jcache.xml";
 
-    private final String cacheKey;
     private final Cache<String, EHCacheValue> cache;
     private final CacheManager cacheManager;
     private final Duration maxTTL;
+    private boolean closed;
 
     public JCacheTokenReplayCache() throws URISyntaxException {
         this(DEFAULT_CONFIG_URL, null);
@@ -91,7 +91,6 @@ public class JCacheTokenReplayCache implements 
TokenReplayCache<String> {
      */
     protected JCacheTokenReplayCache(String cacheKey, String configFile, 
String defaultConfigFile, Bus bus)
         throws URISyntaxException {
-        this.cacheKey = cacheKey;
         if (bus == null) {
             bus = BusFactory.getThreadDefaultBus(true);
         }
@@ -107,11 +106,19 @@ public class JCacheTokenReplayCache implements 
TokenReplayCache<String> {
         URL resolvedConfigFileURL = getConfigFileURL(configFileURL, 
defaultConfigFile);
         URI configURI = resolvedConfigFileURL != null
             ? resolvedConfigFileURL.toURI() : cachingProvider.getDefaultURI();
-        cacheManager = cachingProvider.getCacheManager(configURI, 
getClass().getClassLoader());
+        cacheManager = JCacheUtils.getCacheManager(cachingProvider, configURI, 
getClass().getClassLoader());
 
-        Cache<String, EHCacheValue> configuredCache =
-            cacheManager.getCache(cacheKey, String.class, EHCacheValue.class);
-        cache = configuredCache != null ? configuredCache : 
createCache(cacheManager, cacheKey);
+        try {
+            // a cache the provider does not define is created holding every 
entry for the max TTL (JCache
+            // has no per-entry expiry), rather than forever; a configuration 
(such as the default one) can
+            // still supply its settings, including its expiry, through a 
template for the cache name
+            cache = JCacheUtils.getOrCreate(cacheManager, cacheKey, 
String.class, EHCacheValue.class,
+                configuration -> 
configuration.setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(
+                    new javax.cache.expiry.Duration(TimeUnit.SECONDS, 
EHCacheExpiry.MAX_TTL))));
+        } catch (RuntimeException ex) {
+            JCacheUtils.releaseCacheManager(cacheManager);
+            throw ex;
+        }
 
         // The max TTL is read from the JCache expiry policy of the cache, if 
the provider can return it.
         // Ehcache cannot for a cache whose expiry comes from its own 
configuration, but the default
@@ -163,21 +170,6 @@ public class JCacheTokenReplayCache implements 
TokenReplayCache<String> {
         return maxTTL;
     }
 
-    /**
-     * Create the cache, if the JCache provider does not define it. A 
configuration (such as the default
-     * one) can still supply its settings, including its expiry, through a 
template for the cache name.
-     * Without one, every entry is held for the max TTL (JCache has no 
per-entry expiry), rather than
-     * forever.
-     */
-    private static Cache<String, EHCacheValue> createCache(CacheManager 
cacheManager, String name) {
-        final MutableConfiguration<String, EHCacheValue> cacheConfiguration = 
new MutableConfiguration<>();
-        cacheConfiguration.setTypes(String.class, EHCacheValue.class);
-        
cacheConfiguration.setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(
-            new javax.cache.expiry.Duration(TimeUnit.SECONDS, 
EHCacheExpiry.MAX_TTL)));
-
-        return cacheManager.createCache(name, cacheConfiguration);
-    }
-
     private static URL getConfigFileURL(URL suppliedConfigFileURL, String 
defaultConfigFile) {
         if (suppliedConfigFileURL == null) {
             //using the default
@@ -257,9 +249,10 @@ public class JCacheTokenReplayCache implements 
TokenReplayCache<String> {
     }
 
     public synchronized void close() {
-        if (!cacheManager.isClosed()) {
-            cacheManager.destroyCache(cacheKey);
-            cacheManager.close();
+        if (!closed) {
+            closed = true;
+            JCacheUtils.release(cache);
+            JCacheUtils.releaseCacheManager(cacheManager);
         }
     }
 
diff --git 
a/rt/rs/security/xml/src/test/java/org/apache/cxf/rs/security/common/jcache/JCacheTokenReplayCacheLifecycleTest.java
 
b/rt/rs/security/xml/src/test/java/org/apache/cxf/rs/security/common/jcache/JCacheTokenReplayCacheLifecycleTest.java
new file mode 100644
index 00000000000..23e71b76152
--- /dev/null
+++ 
b/rt/rs/security/xml/src/test/java/org/apache/cxf/rs/security/common/jcache/JCacheTokenReplayCacheLifecycleTest.java
@@ -0,0 +1,76 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.cxf.rs.security.common.jcache;
+
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.time.Instant;
+
+import javax.cache.Cache;
+import javax.cache.CacheManager;
+import javax.cache.Caching;
+import javax.cache.configuration.MutableConfiguration;
+
+import org.apache.wss4j.common.cache.EHCacheValue;
+
+import org.junit.Test;
+
+import static org.junit.Assert.assertTrue;
+
+public class JCacheTokenReplayCacheLifecycleTest {
+    @Test
+    public void testReplayCacheSurvivesOtherUserClosing() throws Exception {
+        JCacheTokenReplayCache replay = new JCacheTokenReplayCache();
+        JCacheTokenReplayCache sameReplay = new JCacheTokenReplayCache();
+        try {
+            replay.putId("retained");
+            replay.close();
+            replay.close();
+            assertTrue(sameReplay.contains("retained"));
+            assertTrue(sameReplay.putIdIfAbsent("added", null));
+            assertTrue(sameReplay.contains("added"));
+        } finally {
+            replay.close();
+            sameReplay.close();
+        }
+    }
+
+    /**
+     * Closing the last user closes the manager of the configuration file, 
which releases its disk
+     * store, so that a redeployed application (another class loader) can 
create it again.
+     */
+    @Test
+    public void testLastCloseReleasesConfiguredManager() throws Exception {
+        JCacheTokenReplayCache replay = new JCacheTokenReplayCache();
+        replay.putId("first");
+        replay.close();
+
+        URL config = 
JCacheTokenReplayCache.class.getResource("/cxf-rs-security-replay-jcache.xml");
+        ClassLoader redeployed = new URLClassLoader(new URL[0], 
JCacheTokenReplayCache.class.getClassLoader());
+        CacheManager manager = 
Caching.getCachingProvider().getCacheManager(config.toURI(), redeployed);
+        try {
+            Cache<String, EHCacheValue> cache = 
manager.createCache(JCacheTokenReplayCache.CACHE_KEY,
+                new MutableConfiguration<String, 
EHCacheValue>().setTypes(String.class, EHCacheValue.class));
+            cache.put("second", new EHCacheValue("second", 
Instant.now().plusSeconds(60)));
+            assertTrue(cache.containsKey("second"));
+        } finally {
+            manager.close();
+        }
+    }
+}
diff --git a/rt/security/pom.xml b/rt/security/pom.xml
index 7b7dacc61f5..95d2e564c8b 100644
--- a/rt/security/pom.xml
+++ b/rt/security/pom.xml
@@ -32,8 +32,16 @@
     </parent>
     <properties>
         <cxf.module.name>org.apache.cxf.security</cxf.module.name>
+        <cxf.osgi.import>javax.cache*;resolution:=optional</cxf.osgi.import>
     </properties>
     <dependencies>
+        <dependency>
+            <groupId>javax.cache</groupId>
+            <artifactId>cache-api</artifactId>
+            <version>${cxf.jcache.version}</version>
+            <scope>provided</scope>
+            <optional>true</optional>
+        </dependency>
         <dependency>
             <groupId>org.apache.cxf</groupId>
             <artifactId>cxf-core</artifactId>
@@ -49,5 +57,12 @@
             <artifactId>junit</artifactId>
             <scope>test</scope>
         </dependency>
+        <dependency>
+            <groupId>org.ehcache</groupId>
+            <artifactId>ehcache</artifactId>
+            <version>${cxf.ehcache3.version}</version>
+            <classifier>jakarta</classifier>
+            <scope>test</scope>
+        </dependency>
     </dependencies>
 </project>
diff --git 
a/rt/security/src/main/java/org/apache/cxf/rt/security/utils/JCacheUtils.java 
b/rt/security/src/main/java/org/apache/cxf/rt/security/utils/JCacheUtils.java
new file mode 100644
index 00000000000..b5f2a81009c
--- /dev/null
+++ 
b/rt/security/src/main/java/org/apache/cxf/rt/security/utils/JCacheUtils.java
@@ -0,0 +1,125 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.cxf.rt.security.utils;
+
+import java.net.URI;
+import java.util.IdentityHashMap;
+import java.util.Map;
+import java.util.function.Function;
+import java.util.function.Supplier;
+
+import javax.cache.Cache;
+import javax.cache.CacheManager;
+import javax.cache.configuration.Configuration;
+import javax.cache.configuration.MutableConfiguration;
+import javax.cache.spi.CachingProvider;
+
+/**
+ * Shared ownership of JCache caches and managers. A cache is destroyed when 
the last user that
+ * obtained it here releases it, if it was created here. A manager obtained 
here for a configuration
+ * URI is closed when its last user releases it; the provider's default 
manager may be shared with
+ * the application, so it is never closed.
+ * <p>
+ * The caches and managers are held strongly until they are released, so every 
user must release
+ * what it obtained here, e.g. by closing the replay cache, token store or 
data provider that uses
+ * it; otherwise they, and the class loader of the application that created 
them, stay reachable
+ * after the application is undeployed.
+ */
+public final class JCacheUtils {
+    private static final Map<Cache<?, ?>, Reference> CACHES = new 
IdentityHashMap<>();
+    private static final Map<CacheManager, Reference> MANAGERS = new 
IdentityHashMap<>();
+
+    private JCacheUtils() {
+    }
+
+    /** Release the manager once with releaseCacheManager. */
+    public static synchronized CacheManager getCacheManager(CachingProvider 
provider, URI uri,
+                                                            ClassLoader 
classLoader) {
+        purgeClosed();
+        CacheManager manager = provider.getCacheManager(uri, classLoader);
+        MANAGERS.computeIfAbsent(manager, m -> new Reference(m, null, 
!uri.equals(provider.getDefaultURI())))
+            .users++;
+        return manager;
+    }
+
+    public static synchronized void releaseCacheManager(CacheManager manager) {
+        Reference reference = MANAGERS.get(manager);
+        if (reference != null && --reference.users == 0) {
+            MANAGERS.remove(manager);
+            if (reference.owned && !manager.isClosed()) {
+                manager.close();
+            }
+            purgeClosed();
+        }
+    }
+
+    public static <K, V> Cache<K, V> getOrCreate(CacheManager manager, String 
name,
+                                               Class<K> keyType, Class<V> 
valueType) {
+        return getOrCreate(manager, name, keyType, valueType, 
Function.identity());
+    }
+
+    public static <K, V> Cache<K, V> getOrCreate(CacheManager manager, String 
name,
+            Class<K> keyType, Class<V> valueType,
+            Function<MutableConfiguration<K, V>, MutableConfiguration<K, V>> 
customizer) {
+        return getOrCreate(manager, name, keyType, valueType,
+            () -> customizer.apply(new MutableConfiguration<K, 
V>().setTypes(keyType, valueType)));
+    }
+
+    /** Release the cache once with release. The configuration is only used to 
create the cache. */
+    public static synchronized <K, V> Cache<K, V> getOrCreate(CacheManager 
manager, String name,
+            Class<K> keyType, Class<V> valueType, Supplier<? extends 
Configuration<K, V>> configuration) {
+        purgeClosed();
+        Cache<K, V> cache = manager.getCache(name, keyType, valueType);
+        boolean owned = cache == null;
+        if (owned) {
+            cache = manager.createCache(name, configuration.get());
+        }
+        CACHES.computeIfAbsent(cache, c -> new Reference(manager, name, 
owned)).users++;
+        return cache;
+    }
+
+    public static synchronized void release(Cache<?, ?> cache) {
+        Reference reference = CACHES.get(cache);
+        if (reference != null && --reference.users == 0) {
+            CACHES.remove(cache);
+            if (reference.owned && !reference.manager.isClosed() && 
!cache.isClosed()) {
+                reference.manager.destroyCache(reference.name);
+            }
+        }
+    }
+
+    // forget the caches and managers that were closed or destroyed by others
+    private static void purgeClosed() {
+        CACHES.keySet().removeIf(Cache::isClosed);
+        MANAGERS.keySet().removeIf(CacheManager::isClosed);
+    }
+
+    private static final class Reference {
+        private final CacheManager manager;
+        private final String name;
+        private final boolean owned;
+        private int users;
+
+        Reference(CacheManager manager, String name, boolean owned) {
+            this.manager = manager;
+            this.name = name;
+            this.owned = owned;
+        }
+    }
+}
diff --git 
a/rt/security/src/test/java/org/apache/cxf/rt/security/utils/JCacheUtilsTest.java
 
b/rt/security/src/test/java/org/apache/cxf/rt/security/utils/JCacheUtilsTest.java
new file mode 100644
index 00000000000..fbd078e32c4
--- /dev/null
+++ 
b/rt/security/src/test/java/org/apache/cxf/rt/security/utils/JCacheUtilsTest.java
@@ -0,0 +1,114 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.cxf.rt.security.utils;
+
+import java.net.URI;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.util.UUID;
+
+import javax.cache.Cache;
+import javax.cache.CacheManager;
+import javax.cache.Caching;
+import javax.cache.configuration.MutableConfiguration;
+import javax.cache.spi.CachingProvider;
+
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotSame;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertTrue;
+
+public class JCacheUtilsTest {
+    @Test
+    public void testConfiguredManagerClosedOnLastRelease() throws Exception {
+        CachingProvider provider = Caching.getCachingProvider();
+        URI config = 
JCacheUtilsTest.class.getResource("/jcache-utils-test.xml").toURI();
+        ClassLoader loader = new URLClassLoader(new URL[0], 
JCacheUtilsTest.class.getClassLoader());
+        CacheManager first = JCacheUtils.getCacheManager(provider, config, 
loader);
+        CacheManager second = JCacheUtils.getCacheManager(provider, config, 
loader);
+        assertSame(first, second);
+        JCacheUtils.releaseCacheManager(first);
+        assertFalse(second.isClosed());
+        JCacheUtils.releaseCacheManager(second);
+        assertTrue(second.isClosed());
+    }
+
+    @Test
+    public void testDefaultManagerIsNeverClosed() {
+        CachingProvider provider = Caching.getCachingProvider();
+        CacheManager manager = JCacheUtils.getCacheManager(provider, 
provider.getDefaultURI(),
+            provider.getDefaultClassLoader());
+        JCacheUtils.releaseCacheManager(manager);
+        assertFalse(manager.isClosed());
+    }
+
+    @Test
+    public void testCacheDestroyedByOthersIsCreatedAgain() {
+        CacheManager manager = Caching.getCachingProvider().getCacheManager();
+        String name = UUID.randomUUID().toString();
+        Cache<String, String> destroyed = JCacheUtils.getOrCreate(manager, 
name, String.class, String.class);
+        manager.destroyCache(name);
+        Cache<String, String> created = JCacheUtils.getOrCreate(manager, name, 
String.class, String.class);
+        assertNotSame(destroyed, created);
+        created.put("key", "value");
+        JCacheUtils.release(destroyed);
+        assertEquals("value", created.get("key"));
+        JCacheUtils.release(created);
+        assertNull(manager.getCache(name));
+    }
+
+    @Test
+    public void testSharedCacheSurvivesUntilLastRelease() {
+        CacheManager manager = Caching.getCachingProvider().getCacheManager();
+        String name = UUID.randomUUID().toString();
+        Cache<String, String> first = JCacheUtils.getOrCreate(manager, name, 
String.class, String.class);
+        Cache<String, String> second = JCacheUtils.getOrCreate(manager, name, 
String.class, String.class);
+        first.put("key", "value");
+        JCacheUtils.release(first);
+        try {
+            assertEquals("value", second.get("key"));
+            assertFalse(manager.isClosed());
+        } finally {
+            JCacheUtils.release(second);
+        }
+        assertNull(manager.getCache(name));
+        assertFalse(manager.isClosed());
+    }
+
+    @Test
+    public void testExternallyCreatedCacheRemainsOwnedByCaller() {
+        CacheManager manager = Caching.getCachingProvider().getCacheManager();
+        String name = UUID.randomUUID().toString();
+        Cache<String, String> external = manager.createCache(name,
+            new MutableConfiguration<String, String>().setTypes(String.class, 
String.class));
+        Cache<String, String> acquired = JCacheUtils.getOrCreate(manager, 
name, String.class, String.class);
+        external.put("key", "value");
+        JCacheUtils.release(acquired);
+        try {
+            assertEquals("value", external.get("key"));
+            assertFalse(manager.isClosed());
+        } finally {
+            manager.destroyCache(name);
+        }
+    }
+}
diff --git a/rt/security/src/test/resources/jcache-utils-test.xml 
b/rt/security/src/test/resources/jcache-utils-test.xml
new file mode 100644
index 00000000000..ff67fae5bf5
--- /dev/null
+++ b/rt/security/src/test/resources/jcache-utils-test.xml
@@ -0,0 +1,20 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  Licensed to the Apache Software Foundation (ASF) under one
+  or more contributor license agreements. See the NOTICE file
+  distributed with this work for additional information
+  regarding copyright ownership. The ASF licenses this file
+  to you under the Apache License, Version 2.0 (the
+  "License"); you may not use this file except in compliance
+  with the License. You may obtain a copy of the License at
+
+  http://www.apache.org/licenses/LICENSE-2.0
+
+  Unless required by applicable law or agreed to in writing,
+  software distributed under the License is distributed on an
+  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+  KIND, either express or implied. See the License for the
+  specific language governing permissions and limitations
+  under the License.
+-->
+<config xmlns="http://www.ehcache.org/v3"/>
diff --git 
a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/cache/jcache/EhcacheReplayExpiry.java
 
b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/cache/jcache/EhcacheReplayExpiry.java
new file mode 100644
index 00000000000..1d18fc315ca
--- /dev/null
+++ 
b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/cache/jcache/EhcacheReplayExpiry.java
@@ -0,0 +1,95 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.cxf.ws.security.cache.jcache;
+
+import java.time.Clock;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.function.Supplier;
+
+import javax.cache.Cache;
+import javax.cache.configuration.Configuration;
+
+import org.apache.wss4j.common.cache.EHCacheExpiry;
+import org.apache.wss4j.common.cache.EHCacheValue;
+import org.ehcache.config.CacheRuntimeConfiguration;
+import org.ehcache.config.builders.CacheConfigurationBuilder;
+import org.ehcache.config.builders.ResourcePoolsBuilder;
+import org.ehcache.expiry.ExpiryPolicy;
+import org.ehcache.jsr107.Eh107Configuration;
+
+/**
+ * Evicts each replay identifier when its own expiry has passed, which a 
JCache expiry policy cannot do
+ * as it does not see the value. Only loaded when the caching provider is 
Ehcache.
+ */
+final class EhcacheReplayExpiry implements ExpiryPolicy<String, EHCacheValue> {
+    private final Clock clock;
+
+    EhcacheReplayExpiry(Clock clock) {
+        this.clock = clock;
+    }
+
+    static Configuration<String, EHCacheValue> configuration(Clock clock) {
+        // unbounded like a JCache MutableConfiguration, as evicting an 
unexpired identifier allows a replay
+        return Eh107Configuration.fromEhcacheCacheConfiguration(
+            
CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, 
EHCacheValue.class,
+                ResourcePoolsBuilder.heap(Long.MAX_VALUE))
+                .withExpiry(new EhcacheReplayExpiry(clock))
+                .build());
+    }
+
+    /** Whether the cache evicts each identifier at its own expiry with this 
policy. */
+    static boolean isUsedBy(Cache<String, EHCacheValue> cache) {
+        try {
+            @SuppressWarnings("unchecked")
+            Eh107Configuration<String, EHCacheValue> configuration = 
cache.getConfiguration(Eh107Configuration.class);
+            return 
configuration.unwrap(CacheRuntimeConfiguration.class).getExpiryPolicy()
+                instanceof EhcacheReplayExpiry;
+        } catch (IllegalArgumentException ex) {
+            return false;
+        }
+    }
+
+    @Override
+    public Duration getExpiryForCreation(String key, EHCacheValue value) {
+        return remaining(value);
+    }
+
+    @Override
+    public Duration getExpiryForAccess(String key, Supplier<? extends 
EHCacheValue> value) {
+        return null;
+    }
+
+    // unlike EHCacheExpiry, a replaced identifier gets the expiry of its new 
value
+    @Override
+    public Duration getExpiryForUpdate(String key, Supplier<? extends 
EHCacheValue> oldValue,
+                                       EHCacheValue newValue) {
+        return remaining(newValue);
+    }
+
+    private Duration remaining(EHCacheValue value) {
+        Instant expiry = value.getExpiry();
+        if (expiry == null) {
+            return Duration.ofSeconds(EHCacheExpiry.DEFAULT_TTL);
+        }
+        Duration remaining = Duration.between(clock.instant(), expiry);
+        return remaining.isNegative() ? Duration.ZERO : remaining;
+    }
+}
diff --git 
a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/cache/jcache/JCacheReplayCache.java
 
b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/cache/jcache/JCacheReplayCache.java
index ac0ba68a36d..e2de6f511d4 100644
--- 
a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/cache/jcache/JCacheReplayCache.java
+++ 
b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/cache/jcache/JCacheReplayCache.java
@@ -19,6 +19,8 @@
 
 package org.apache.cxf.ws.security.cache.jcache;
 
+import java.io.Serializable;
+import java.time.Clock;
 import java.time.Instant;
 import java.util.Objects;
 import java.util.concurrent.TimeUnit;
@@ -26,11 +28,15 @@ import java.util.concurrent.TimeUnit;
 import javax.cache.Cache;
 import javax.cache.CacheManager;
 import javax.cache.Caching;
+import javax.cache.configuration.Configuration;
+import javax.cache.configuration.MutableConfiguration;
 import javax.cache.expiry.Duration;
-import javax.cache.expiry.ExpiryPolicy;
+import javax.cache.expiry.ModifiedExpiryPolicy;
+import javax.cache.processor.EntryProcessor;
+import javax.cache.processor.MutableEntry;
 import javax.cache.spi.CachingProvider;
 
-import org.apache.cxf.ws.security.utils.JCacheSupport;
+import org.apache.cxf.rt.security.utils.JCacheUtils;
 import org.apache.wss4j.common.cache.EHCacheExpiry;
 import org.apache.wss4j.common.cache.EHCacheValue;
 import org.apache.wss4j.common.cache.ReplayCache;
@@ -38,48 +44,71 @@ import org.apache.wss4j.common.ext.WSSecurityException;
 
 /**
  * An in-memory JCache based implementation of the ReplayCache interface.
- * The default TTL is 60 minutes and the max TTL is 12 hours.
+ * The default TTL is 60 minutes and the max TTL is 12 hours. With Ehcache 
(the same copy that CXF sees),
+ * each identifier is held until its own expiry, up to the max TTL; with other 
providers, every identifier
+ * is held for the default TTL.
  */
 class JCacheReplayCache implements ReplayCache {
     private static final org.slf4j.Logger LOG =
             org.slf4j.LoggerFactory.getLogger(JCacheReplayCache.class);
+    private static final String EHCACHE_PROVIDER = 
"org.ehcache.jsr107.EhcacheCachingProvider";
+    private static final String[] EHCACHE_CLASSES = {
+        "org.ehcache.jsr107.Eh107Configuration", 
"org.ehcache.expiry.ExpiryPolicy"
+    };
 
     private final Cache<String, EHCacheValue> cache;
     private final CacheManager cacheManager;
-    private final String key;
+    private final Clock clock;
+    private final boolean entryExpiry;
+    private boolean closed;
 
     JCacheReplayCache(String key) throws WSSecurityException {
         this(key, 10000);
     }
 
     JCacheReplayCache(String key, long heapEntries) throws WSSecurityException 
{
-        this.key = Objects.requireNonNull(key);
+        this(key, heapEntries, Clock.systemUTC());
+    }
+
+    JCacheReplayCache(String key, long heapEntries, Clock clock) throws 
WSSecurityException {
+        this(key, clock, null);
+    }
+
+    /**
+     * @param ehcacheExpiry whether to use Ehcache's per-entry expiry, or null 
to use it if the provider is
+     *                      the same copy of Ehcache that CXF sees
+     */
+    JCacheReplayCache(String key, Clock clock, Boolean ehcacheExpiry) throws 
WSSecurityException {
+        Objects.requireNonNull(key);
+        this.clock = Objects.requireNonNull(clock);
 
         // Do some checking on the arguments
+        Cache<String, EHCacheValue> acquired = null;
         try {
             final CachingProvider cachingProvider = 
Caching.getCachingProvider();
-            cacheManager = cachingProvider.getCacheManager(); 
-            cache = JCacheSupport.getOrCreate(cacheManager, key, String.class, 
EHCacheValue.class,
-                cacheConfiguration -> 
cacheConfiguration.setExpiryPolicyFactory(() -> new ExpiryPolicy() {
-                    @Override
-                    public Duration getExpiryForCreation() {
-                        return new Duration(TimeUnit.SECONDS, 
EHCacheExpiry.DEFAULT_TTL);
-                    }
-                    
-                    @Override
-                    public Duration getExpiryForAccess() {
-                        return null;
-                    }
-                    
-                    @Override
-                    public Duration getExpiryForUpdate() {
-                        return null;
-                    }
-                }));
+            cacheManager = cachingProvider.getCacheManager();
+            Cache<String, EHCacheValue> entryExpiryCache = null;
+            if (ehcacheExpiry != null ? ehcacheExpiry : 
isSameEhcache(cachingProvider)) {
+                try {
+                    entryExpiryCache = JCacheUtils.getOrCreate(cacheManager, 
key, String.class, EHCacheValue.class,
+                        () -> EhcacheReplayExpiry.configuration(clock));
+                } catch (LinkageError | IllegalArgumentException | 
ClassCastException ex) {
+                    LOG.warn("Ehcache per-entry expiry is not available for 
the replay cache, every identifier "
+                        + "is held for the default TTL: {}", ex.toString());
+                }
+            }
+            acquired = entryExpiryCache != null ? entryExpiryCache : 
JCacheUtils.getOrCreate(cacheManager, key,
+                String.class, EHCacheValue.class, 
JCacheReplayCache::defaultTtlConfiguration);
+            // the cache may already exist with another configuration, so 
check the one it has
+            entryExpiry = entryExpiryCache != null && 
EhcacheReplayExpiry.isUsedBy(entryExpiryCache);
         } catch (Exception ex) {
+            if (acquired != null) {
+                JCacheUtils.release(acquired);
+            }
             LOG.error("Error configuring JCacheReplayCache: {}", 
ex.getMessage());
             throw new 
WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ex, 
"replayCacheError");
         }
+        cache = acquired;
     }
 
     /**
@@ -100,7 +129,7 @@ class JCacheReplayCache implements ReplayCache {
             return;
         }
 
-        cache.put(identifier, new EHCacheValue(identifier, expiry));
+        cache.put(identifier, value(identifier, expiry, clock.instant()));
     }
 
     /**
@@ -118,7 +147,8 @@ class JCacheReplayCache implements ReplayCache {
             return false;
         }
 
-        return cache.putIfAbsent(identifier, new EHCacheValue(identifier, 
expiry));
+        Instant now = clock.instant();
+        return cache.invoke(identifier, new AddIfAbsent(), value(identifier, 
expiry, now), now);
     }
 
     /**
@@ -126,33 +156,110 @@ class JCacheReplayCache implements ReplayCache {
      * @param identifier The identifier to check
      */
     public boolean contains(String identifier) {
-        if (cache == null) {
-            return false;
-        }
-        EHCacheValue element = cache.get(identifier);
-        return element != null;
+        return get(identifier) != null;
     }
 
     /**
      * Return the maximum time for which this cache holds an identifier. WSS4J 
uses this to reject a
      * SAML OneTimeUse Assertion that is valid for longer, as it could be 
replayed once its identifier
-     * had expired from the cache. This implements ReplayCache.getMaxTTL() in 
versions of WSS4J that
-     * define it, so it is declared without @Override.
+     * had expired from the cache. With Ehcache's per-entry expiry an 
identifier is held until its own
+     * expiry, up to the max TTL; otherwise it is held for the default TTL. 
This implements
+     * ReplayCache.getMaxTTL() in versions of WSS4J that define it, so it is 
declared without @Override.
      */
     public java.time.Duration getMaxTTL() {
-        return java.time.Duration.ofSeconds(EHCacheExpiry.DEFAULT_TTL);
+        return java.time.Duration.ofSeconds(entryExpiry ? 
EHCacheExpiry.MAX_TTL : EHCacheExpiry.DEFAULT_TTL);
     }
 
     // Only exposed for testing
     EHCacheValue get(String identifier) {
-        return cache.get(identifier);
+        return cache.invoke(identifier, new ReadEntry(), clock.instant());
     }
 
     @Override
     public synchronized void close() {
-        if (!cacheManager.isClosed()) {
-            cacheManager.destroyCache(key);
-            cacheManager.close();
+        if (!closed) {
+            closed = true;
+            JCacheUtils.release(cache);
+        }
+    }
+
+    /**
+     * Entry processors enforce the expiry of each identifier atomically. A 
JCache expiry policy cannot
+     * inspect values, so without Ehcache's per-entry expiry every identifier 
is held for the default TTL
+     * from when it was last written (an identifier with a shorter expiry is 
treated as absent once it has
+     * passed), and getMaxTTL reports the default TTL.
+     */
+    private static Configuration<String, EHCacheValue> 
defaultTtlConfiguration() {
+        return new MutableConfiguration<String, EHCacheValue>()
+            .setTypes(String.class, EHCacheValue.class)
+            .setExpiryPolicyFactory(ModifiedExpiryPolicy.factoryOf(
+                new Duration(TimeUnit.SECONDS, EHCacheExpiry.DEFAULT_TTL)));
+    }
+
+    /**
+     * Whether the provider is Ehcache, loaded from the same classes as CXF 
sees: otherwise (an unwired
+     * optional OSGi import, or Ehcache in an application with CXF in a shared 
library) CXF cannot build an
+     * Ehcache configuration the provider accepts.
+     */
+    static boolean isSameEhcache(CachingProvider provider) {
+        if (!EHCACHE_PROVIDER.equals(provider.getClass().getName())) {
+            return false;
+        }
+        for (String name : EHCACHE_CLASSES) {
+            if (!isSameClass(name, JCacheReplayCache.class.getClassLoader(), 
provider.getClass().getClassLoader())) {
+                return false;
+            }
+        }
+        return true;
+    }
+
+    static boolean isSameClass(String name, ClassLoader ours, ClassLoader 
theirs) {
+        try {
+            return Class.forName(name, false, ours) == Class.forName(name, 
false, theirs);
+        } catch (ClassNotFoundException | LinkageError ex) {
+            return false;
+        }
+    }
+
+    private EHCacheValue value(String identifier, Instant expiry, Instant now) 
{
+        // as EHCacheExpiry does, an expiry that is not in the future gets the 
default TTL
+        if (expiry == null || !expiry.isAfter(now) || 
expiry.isAfter(now.plusSeconds(EHCacheExpiry.MAX_TTL))) {
+            expiry = now.plusSeconds(EHCacheExpiry.DEFAULT_TTL);
+        }
+        return new EHCacheValue(identifier, expiry);
+    }
+
+    private static boolean expired(EHCacheValue value, Instant now) {
+        return value.getExpiry() != null && !value.getExpiry().isAfter(now);
+    }
+
+    private static final class ReadEntry implements EntryProcessor<String, 
EHCacheValue, EHCacheValue>, Serializable {
+        private static final long serialVersionUID = 1L;
+
+        @Override
+        public EHCacheValue process(MutableEntry<String, EHCacheValue> entry, 
Object... arguments) {
+            if (!entry.exists()) {
+                return null;
+            }
+            EHCacheValue value = entry.getValue();
+            if (expired(value, (Instant)arguments[0])) {
+                entry.remove();
+                return null;
+            }
+            return value;
+        }
+    }
+
+    private static final class AddIfAbsent implements EntryProcessor<String, 
EHCacheValue, Boolean>, Serializable {
+        private static final long serialVersionUID = 1L;
+
+        @Override
+        public Boolean process(MutableEntry<String, EHCacheValue> entry, 
Object... arguments) {
+            if (entry.exists() && !expired(entry.getValue(), 
(Instant)arguments[1])) {
+                return false;
+            }
+            entry.setValue((EHCacheValue)arguments[0]);
+            return true;
         }
     }
 
diff --git 
a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/tokenstore/jcache/JCacheTokenStore.java
 
b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/tokenstore/jcache/JCacheTokenStore.java
index 25c29aa7714..7000efc49bf 100644
--- 
a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/tokenstore/jcache/JCacheTokenStore.java
+++ 
b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/tokenstore/jcache/JCacheTokenStore.java
@@ -34,6 +34,7 @@ import org.apache.cxf.Bus;
 import org.apache.cxf.buslifecycle.BusLifeCycleListener;
 import org.apache.cxf.buslifecycle.BusLifeCycleManager;
 import org.apache.cxf.common.util.StringUtils;
+import org.apache.cxf.rt.security.utils.JCacheUtils;
 import org.apache.cxf.ws.security.tokenstore.SecurityToken;
 import org.apache.cxf.ws.security.tokenstore.TokenStore;
 import org.apache.cxf.ws.security.tokenstore.TokenStoreException;
@@ -47,7 +48,7 @@ public class JCacheTokenStore implements TokenStore, 
Closeable, BusLifeCycleList
     private final Bus bus;
     private final Cache<String, SecurityToken> cache;
     private final CacheManager cacheManager;
-    private final String key;
+    private boolean closed;
 
     public JCacheTokenStore(String key, Bus b, URL configFileURL) throws 
TokenStoreException {
         bus = b;
@@ -55,7 +56,6 @@ public class JCacheTokenStore implements TokenStore, 
Closeable, BusLifeCycleList
             
b.getExtension(BusLifeCycleManager.class).registerLifeCycleListener(this);
         }
 
-        this.key = key;
         try {
             // Exclude the endpoint info bit added in TokenStoreUtils when 
getting the template name
             String template = key;
@@ -64,12 +64,17 @@ public class JCacheTokenStore implements TokenStore, 
Closeable, BusLifeCycleList
             }
 
             final CachingProvider cachingProvider = 
Caching.getCachingProvider();
-            cacheManager = 
cachingProvider.getCacheManager(configFileURL.toURI(),
-                    SecurityToken.class.getClassLoader()); 
-            cache = JCacheSupport.getOrCreate(cacheManager, key, String.class, 
SecurityToken.class);
+            cacheManager = JCacheUtils.getCacheManager(cachingProvider, 
configFileURL.toURI(),
+                    SecurityToken.class.getClassLoader());
         } catch (Exception e) {
             throw new TokenStoreException(e);
         }
+        try {
+            cache = JCacheSupport.getOrCreate(cacheManager, key, String.class, 
SecurityToken.class);
+        } catch (RuntimeException e) {
+            JCacheUtils.releaseCacheManager(cacheManager);
+            throw new TokenStoreException(e);
+        }
     }
 
     public void add(SecurityToken token) {
@@ -112,10 +117,12 @@ public class JCacheTokenStore implements TokenStore, 
Closeable, BusLifeCycleList
     }
 
     public synchronized void close() {
-        if (!cacheManager.isClosed()) {
-            cacheManager.destroyCache(key);
-            cacheManager.close();
+        if (closed) {
+            return;
         }
+        closed = true;
+        JCacheUtils.release(cache);
+        JCacheUtils.releaseCacheManager(cacheManager);
 
         if (bus != null) {
             
bus.getExtension(BusLifeCycleManager.class).unregisterLifeCycleListener(this);
diff --git 
a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/utils/JCacheSupport.java
 
b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/utils/JCacheSupport.java
index 95cedb378cb..1fe33a76c95 100644
--- 
a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/utils/JCacheSupport.java
+++ 
b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/utils/JCacheSupport.java
@@ -24,6 +24,8 @@ import javax.cache.Cache;
 import javax.cache.CacheManager;
 import javax.cache.configuration.MutableConfiguration;
 
+import org.apache.cxf.rt.security.utils.JCacheUtils;
+
 public final class JCacheSupport {
     private JCacheSupport() {
     }
@@ -36,14 +38,6 @@ public final class JCacheSupport {
     public static <K, V> Cache<K, V> getOrCreate(CacheManager cacheManager, 
String name, Class<K> kclass,
             Class<V> vclass, Function<MutableConfiguration<K, V>, 
MutableConfiguration<K, V>> customizer) {
 
-        final Cache<K, V> cache = cacheManager.getCache(name, kclass, vclass);
-        if (cache != null) {
-            return cache;
-        }
-
-        MutableConfiguration<K, V> cacheConfiguration = new 
MutableConfiguration<>();
-        cacheConfiguration = 
customizer.apply(cacheConfiguration.setTypes(kclass, vclass));
-
-        return cacheManager.createCache(name, cacheConfiguration);
+        return JCacheUtils.getOrCreate(cacheManager, name, kclass, vclass, 
customizer);
     }
 }
diff --git 
a/rt/ws/security/src/test/java/org/apache/cxf/ws/security/cache/jcache/JCacheReplayCacheTest.java
 
b/rt/ws/security/src/test/java/org/apache/cxf/ws/security/cache/jcache/JCacheReplayCacheTest.java
index 8aba1daeb1a..3612032bd23 100644
--- 
a/rt/ws/security/src/test/java/org/apache/cxf/ws/security/cache/jcache/JCacheReplayCacheTest.java
+++ 
b/rt/ws/security/src/test/java/org/apache/cxf/ws/security/cache/jcache/JCacheReplayCacheTest.java
@@ -18,7 +18,13 @@
  */
 package org.apache.cxf.ws.security.cache.jcache;
 
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.time.Clock;
 import java.time.Duration;
+import java.time.Instant;
+import java.time.ZoneId;
+import java.time.ZoneOffset;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.UUID;
@@ -26,14 +32,21 @@ import java.util.concurrent.CyclicBarrier;
 import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Executors;
 import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicIntegerArray;
 
+import javax.cache.Cache;
+import javax.cache.Caching;
+import javax.cache.configuration.CompleteConfiguration;
+
 import org.apache.wss4j.common.cache.EHCacheExpiry;
+import org.apache.wss4j.common.cache.EHCacheValue;
 
 import org.junit.Test;
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertTrue;
 
 /**
@@ -41,6 +54,189 @@ import static org.junit.Assert.assertTrue;
  */
 public class JCacheReplayCacheTest {
 
+    @Test
+    public void testClosingOtherCacheAndRepeatedClose() throws Exception {
+        String name = UUID.randomUUID().toString();
+        JCacheReplayCache first = new JCacheReplayCache(name);
+        JCacheReplayCache same = new JCacheReplayCache(name);
+        JCacheReplayCache different = new 
JCacheReplayCache(UUID.randomUUID().toString());
+        try {
+            first.add("same");
+            different.add("different");
+            first.close();
+            first.close();
+            assertTrue(same.contains("same"));
+            assertTrue(different.contains("different"));
+        } finally {
+            first.close();
+            same.close();
+            different.close();
+        }
+    }
+
+    @Test
+    public void testExplicitExpiryAndReplacement() throws Exception {
+        TestClock clock = new TestClock();
+        JCacheReplayCache cache = new 
JCacheReplayCache(UUID.randomUUID().toString(), 10000, clock);
+        try {
+            cache.add("short", clock.instant().plusSeconds(1));
+            assertTrue(cache.addIfAbsent("atomic", 
clock.instant().plusSeconds(1)));
+            assertTrue(cache.contains("short"));
+            clock.advance(2);
+            assertFalse(cache.contains("short"));
+            assertTrue(cache.addIfAbsent("atomic", 
clock.instant().plusSeconds(30)));
+            assertFalse(cache.addIfAbsent("atomic", null));
+            clock.advance(31);
+            assertFalse(cache.contains("atomic"));
+        } finally {
+            cache.close();
+        }
+    }
+
+    @Test
+    public void testLongExpiryAndDefaultBounds() throws Exception {
+        TestClock clock = new TestClock();
+        JCacheReplayCache cache = new 
JCacheReplayCache(UUID.randomUUID().toString(), 10000, clock);
+        try {
+            Instant longExpiry = clock.instant().plusSeconds(7200);
+            cache.add("long", longExpiry);
+            cache.add("default");
+            cache.add("past", clock.instant().minusSeconds(1));
+            cache.add("now", clock.instant());
+            cache.add("too-long", clock.instant().plusSeconds(43201));
+            assertEquals(longExpiry, cache.get("long").getExpiry());
+            assertEquals(clock.instant().plusSeconds(3600), 
cache.get("past").getExpiry());
+            assertEquals(cache.get("past").getExpiry(), 
cache.get("now").getExpiry());
+            assertEquals(cache.get("past").getExpiry(), 
cache.get("too-long").getExpiry());
+            clock.advance(3601);
+            assertTrue(cache.contains("long"));
+            assertFalse(cache.contains("default"));
+            assertFalse(cache.contains("past"));
+            clock.advance(3600);
+            assertFalse(cache.contains("long"));
+        } finally {
+            cache.close();
+        }
+    }
+
+    /**
+     * Ehcache evicts an identifier at its own expiry, even if it is not 
looked up again, and a
+     * replaced identifier gets the expiry of its new value.
+     */
+    @Test
+    public void testEhcacheEvictsAtEntryExpiry() throws Exception {
+        String name = UUID.randomUUID().toString();
+        JCacheReplayCache cache = new JCacheReplayCache(name);
+        try {
+            Cache<String, EHCacheValue> store = 
Caching.getCachingProvider().getCacheManager()
+                .getCache(name, String.class, EHCacheValue.class);
+            cache.add("short", Instant.now().plusSeconds(1));
+            cache.add("replaced", Instant.now().plusSeconds(1));
+            cache.add("replaced", Instant.now().plusSeconds(60));
+            // poll rather than sleep a fixed time, so that a slow machine 
does not fail the test
+            long deadline = System.currentTimeMillis() + 30000;
+            while (store.containsKey("short") && System.currentTimeMillis() < 
deadline) {
+                Thread.sleep(100);
+            }
+            assertFalse(store.containsKey("short"));
+            assertTrue(store.containsKey("replaced"));
+        } finally {
+            cache.close();
+        }
+    }
+
+    // The expiry Ehcache is given for each identifier, on the test clock
+    @Test
+    public void testEhcacheExpiryDurations() {
+        TestClock clock = new TestClock();
+        EhcacheReplayExpiry expiry = new EhcacheReplayExpiry(clock);
+        Instant now = clock.instant();
+        EHCacheValue shortValue = new EHCacheValue("id", now.plusSeconds(30));
+        EHCacheValue longValue = new EHCacheValue("id", now.plusSeconds(7200));
+        assertEquals(Duration.ofSeconds(30), expiry.getExpiryForCreation("id", 
shortValue));
+        assertEquals(Duration.ofSeconds(7200), expiry.getExpiryForUpdate("id", 
() -> shortValue, longValue));
+        assertEquals(Duration.ofSeconds(EHCacheExpiry.DEFAULT_TTL),
+            expiry.getExpiryForCreation("id", new EHCacheValue("id", null)));
+        clock.advance(31);
+        assertEquals(Duration.ZERO, expiry.getExpiryForCreation("id", 
shortValue));
+        assertNull(expiry.getExpiryForAccess("id", () -> longValue));
+    }
+
+    // Without Ehcache's per-entry expiry, every identifier is held for the 
default TTL, which is reported
+    @Test
+    public void testDefaultTtlWithoutEhcacheExpiry() throws Exception {
+        TestClock clock = new TestClock();
+        String name = "cxf.jcache.replay.test-" + UUID.randomUUID();
+        JCacheReplayCache cache = new JCacheReplayCache(name, clock, false);
+        try {
+            assertEquals(Duration.ofSeconds(EHCacheExpiry.DEFAULT_TTL), 
cache.getMaxTTL());
+            Cache<String, EHCacheValue> store = 
Caching.getCachingProvider().getCacheManager()
+                .getCache(name, String.class, EHCacheValue.class);
+            @SuppressWarnings("unchecked")
+            CompleteConfiguration<String, EHCacheValue> configuration =
+                store.getConfiguration(CompleteConfiguration.class);
+            javax.cache.expiry.ExpiryPolicy policy = 
configuration.getExpiryPolicyFactory().create();
+            assertEquals(new javax.cache.expiry.Duration(TimeUnit.SECONDS, 
EHCacheExpiry.DEFAULT_TTL),
+                policy.getExpiryForCreation());
+            assertEquals(policy.getExpiryForCreation(), 
policy.getExpiryForUpdate());
+
+            // an identifier is still treated as absent once its own, shorter, 
expiry has passed
+            assertTrue(cache.addIfAbsent("id", 
clock.instant().plusSeconds(60)));
+            assertFalse(cache.addIfAbsent("id", null));
+            clock.advance(60);
+            assertFalse(cache.contains("id"));
+        } finally {
+            cache.close();
+        }
+    }
+
+    // A cache that already exists without the per-entry expiry is reported 
with the default TTL
+    @Test
+    public void testExistingCacheWithoutEhcacheExpiry() throws Exception {
+        String name = "cxf.jcache.replay.test-" + UUID.randomUUID();
+        JCacheReplayCache first = new JCacheReplayCache(name, 
Clock.systemUTC(), false);
+        JCacheReplayCache second = new JCacheReplayCache(name, 
Clock.systemUTC(), null);
+        try {
+            assertEquals(Duration.ofSeconds(EHCacheExpiry.DEFAULT_TTL), 
second.getMaxTTL());
+        } finally {
+            first.close();
+            second.close();
+        }
+    }
+
+    @Test
+    public void testEhcacheDetection() {
+        
assertTrue(JCacheReplayCache.isSameEhcache(Caching.getCachingProvider()));
+        String name = "org.ehcache.jsr107.Eh107Configuration";
+        ClassLoader ours = JCacheReplayCache.class.getClassLoader();
+        assertTrue(JCacheReplayCache.isSameClass(name, ours, ours));
+        // a class loader that cannot see Ehcache, as with an unwired optional 
OSGi import
+        assertFalse(JCacheReplayCache.isSameClass(name, ours, new 
URLClassLoader(new URL[0], null)));
+    }
+
+    private static final class TestClock extends Clock {
+        private Instant now = Instant.now();
+
+        void advance(long seconds) {
+            now = now.plusSeconds(seconds);
+        }
+
+        @Override
+        public ZoneId getZone() {
+            return ZoneOffset.UTC;
+        }
+
+        @Override
+        public Clock withZone(ZoneId zone) {
+            return Clock.fixed(now, zone);
+        }
+
+        @Override
+        public Instant instant() {
+            return now;
+        }
+    }
+
     @Test
     public void testAddIfAbsent() throws Exception {
         JCacheReplayCache replayCache = new 
JCacheReplayCache("cxf.jcache.replay.test-" + UUID.randomUUID());
@@ -70,7 +266,18 @@ public class JCacheReplayCacheTest {
      */
     @Test
     public void testConcurrentAddIfAbsent() throws Exception {
-        JCacheReplayCache replayCache = new 
JCacheReplayCache("cxf.jcache.replay.test-" + UUID.randomUUID());
+        assertConcurrentAddIfAbsent(false);
+    }
+
+    @Test
+    public void testConcurrentAddIfAbsentAfterExpiry() throws Exception {
+        assertConcurrentAddIfAbsent(true);
+    }
+
+    private void assertConcurrentAddIfAbsent(boolean expired) throws Exception 
{
+        TestClock clock = new TestClock();
+        JCacheReplayCache replayCache = new JCacheReplayCache(
+            "cxf.jcache.replay.test-" + UUID.randomUUID(), 10000, clock);
 
         final int threads = 8;
         final int identifiers = 500;
@@ -78,6 +285,12 @@ public class JCacheReplayCacheTest {
         for (int i = 0; i < identifiers; i++) {
             ids.add(UUID.randomUUID().toString());
         }
+        if (expired) {
+            for (String id : ids) {
+                replayCache.add(id, clock.instant().plusSeconds(1));
+            }
+            clock.advance(2);
+        }
         AtomicIntegerArray accepted = new AtomicIntegerArray(identifiers);
         CyclicBarrier barrier = new CyclicBarrier(threads);
 
@@ -108,12 +321,20 @@ public class JCacheReplayCacheTest {
         }
     }
 
-    // The cache keeps every entry for the default TTL, so that is the longest 
it can hold one for
+    // An identifier whose expiry is the max TTL away is held until then
     @Test
     public void testMaxTTL() throws Exception {
-        JCacheReplayCache replayCache = new 
JCacheReplayCache("cxf.jcache.replay.test-" + UUID.randomUUID());
+        TestClock clock = new TestClock();
+        JCacheReplayCache replayCache =
+            new JCacheReplayCache("cxf.jcache.replay.test-" + 
UUID.randomUUID(), 10000, clock);
         try {
-            assertEquals(Duration.ofSeconds(EHCacheExpiry.DEFAULT_TTL), 
replayCache.getMaxTTL());
+            Duration maxTTL = replayCache.getMaxTTL();
+            assertEquals(Duration.ofSeconds(EHCacheExpiry.MAX_TTL), maxTTL);
+            assertTrue(replayCache.addIfAbsent("id", 
clock.instant().plus(maxTTL)));
+            clock.advance(maxTTL.getSeconds() - 1);
+            assertFalse(replayCache.addIfAbsent("id", 
clock.instant().plusSeconds(60)));
+            clock.advance(1);
+            assertFalse(replayCache.contains("id"));
         } finally {
             replayCache.close();
         }
diff --git 
a/rt/ws/security/src/test/java/org/apache/cxf/ws/security/tokenstore/jcache/JCacheTokenStoreLifecycleTest.java
 
b/rt/ws/security/src/test/java/org/apache/cxf/ws/security/tokenstore/jcache/JCacheTokenStoreLifecycleTest.java
new file mode 100644
index 00000000000..ef3f7bd4e16
--- /dev/null
+++ 
b/rt/ws/security/src/test/java/org/apache/cxf/ws/security/tokenstore/jcache/JCacheTokenStoreLifecycleTest.java
@@ -0,0 +1,51 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.cxf.ws.security.tokenstore.jcache;
+
+import java.net.URL;
+import java.util.UUID;
+
+import org.apache.cxf.ws.security.tokenstore.SecurityToken;
+
+import org.junit.Test;
+
+import static org.junit.Assert.assertNotNull;
+
+public class JCacheTokenStoreLifecycleTest {
+    @Test
+    public void testSharedAndDistinctStoresSurviveClose() throws Exception {
+        URL config = getClass().getResource("/cxf-jcache.xml");
+        String key = UUID.randomUUID().toString();
+        JCacheTokenStore first = new JCacheTokenStore(key, null, config);
+        JCacheTokenStore same = new JCacheTokenStore(key, null, config);
+        JCacheTokenStore different = new 
JCacheTokenStore(UUID.randomUUID().toString(), null, config);
+        try {
+            first.add(new SecurityToken("same"));
+            different.add(new SecurityToken("different"));
+            first.close();
+            first.close();
+            assertNotNull(same.getToken("same"));
+            assertNotNull(different.getToken("different"));
+        } finally {
+            first.close();
+            same.close();
+            different.close();
+        }
+    }
+}
diff --git 
a/services/sts/sts-core/src/main/java/org/apache/cxf/sts/cache/jcache/JCacheIdentityCache.java
 
b/services/sts/sts-core/src/main/java/org/apache/cxf/sts/cache/jcache/JCacheIdentityCache.java
index 6be3cf153cd..27b19a0f466 100644
--- 
a/services/sts/sts-core/src/main/java/org/apache/cxf/sts/cache/jcache/JCacheIdentityCache.java
+++ 
b/services/sts/sts-core/src/main/java/org/apache/cxf/sts/cache/jcache/JCacheIdentityCache.java
@@ -44,6 +44,7 @@ import org.apache.cxf.management.ManagementConstants;
 import org.apache.cxf.management.annotation.ManagedOperation;
 import org.apache.cxf.management.annotation.ManagedResource;
 import org.apache.cxf.resource.ResourceManager;
+import org.apache.cxf.rt.security.utils.JCacheUtils;
 import org.apache.cxf.sts.IdentityMapper;
 import org.apache.cxf.sts.cache.AbstractIdentityCache;
 import org.apache.cxf.sts.cache.EHCacheIdentityValue;
@@ -62,6 +63,7 @@ public class JCacheIdentityCache extends AbstractIdentityCache
     private static final String KEY = 
"org.apache.cxf.sts.cache.EHCacheIdentityCache";
     private Cache<String, EHCacheIdentityValue> cache;
     private final CacheManager cacheManager;
+    private boolean closed;
 
 
     public JCacheIdentityCache(
@@ -91,11 +93,17 @@ public class JCacheIdentityCache extends 
AbstractIdentityCache
 
         final URL xmlConfigURL = configFileURL != null ? configFileURL : 
getDefaultConfigFileURL();
         try {
-            cacheManager = 
cachingProvider.getCacheManager(xmlConfigURL.toURI(), 
getClass().getClassLoader());
-            cache = JCacheSupport.getOrCreate(cacheManager, KEY, String.class, 
EHCacheIdentityValue.class);
+            cacheManager = JCacheUtils.getCacheManager(cachingProvider, 
xmlConfigURL.toURI(),
+                getClass().getClassLoader());
         } catch (final URISyntaxException ex) {
             throw new IllegalStateException("Unable to convert " + 
xmlConfigURL + " to URI", ex);
-        } 
+        }
+        try {
+            cache = JCacheSupport.getOrCreate(cacheManager, KEY, String.class, 
EHCacheIdentityValue.class);
+        } catch (RuntimeException ex) {
+            JCacheUtils.releaseCacheManager(cacheManager);
+            throw ex;
+        }
     }
 
     @Override
@@ -125,9 +133,10 @@ public class JCacheIdentityCache extends 
AbstractIdentityCache
     }
 
     public synchronized void close() {
-        if (!cacheManager.isClosed()) {
-            cacheManager.destroyCache(KEY);
-            cacheManager.close();
+        if (!closed) {
+            closed = true;
+            JCacheUtils.release(cache);
+            JCacheUtils.releaseCacheManager(cacheManager);
 
             if (super.getBus() != null) {
                 
super.getBus().getExtension(BusLifeCycleManager.class).unregisterLifeCycleListener(this);
diff --git 
a/services/sts/sts-core/src/test/java/org/apache/cxf/sts/cache/jcache/JCacheIdentityCacheLifecycleTest.java
 
b/services/sts/sts-core/src/test/java/org/apache/cxf/sts/cache/jcache/JCacheIdentityCacheLifecycleTest.java
new file mode 100644
index 00000000000..14079d70385
--- /dev/null
+++ 
b/services/sts/sts-core/src/test/java/org/apache/cxf/sts/cache/jcache/JCacheIdentityCacheLifecycleTest.java
@@ -0,0 +1,53 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.cxf.sts.cache.jcache;
+
+import java.util.Collections;
+import java.util.Map;
+
+import org.apache.cxf.Bus;
+import org.apache.cxf.BusFactory;
+import org.ehcache.jsr107.EhcacheCachingProvider;
+
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+
+public class JCacheIdentityCacheLifecycleTest {
+
+    // Both caches share the named cache of the default configuration: closing 
one leaves it to the other
+    @Test
+    public void testClosingOneCacheLeavesTheOtherUsable() {
+        Bus bus = BusFactory.getDefaultBus();
+        EhcacheCachingProvider provider = new EhcacheCachingProvider();
+        JCacheIdentityCache first = new JCacheIdentityCache(provider, null, 
"first", bus, null);
+        JCacheIdentityCache second = new JCacheIdentityCache(provider, null, 
"second", bus, null);
+        try {
+            Map<String, String> identities = 
Collections.singletonMap("realmB", "bob");
+            first.add("alice", "realmA", identities);
+            first.close();
+            first.close();
+            assertEquals(identities, second.get("alice", "realmA"));
+        } finally {
+            first.close();
+            second.close();
+            provider.close();
+        }
+    }
+}
diff --git 
a/services/xkms/xkms-client/src/main/java/org/apache/cxf/xkms/cache/jcache/JCacheXKMSClientCache.java
 
b/services/xkms/xkms-client/src/main/java/org/apache/cxf/xkms/cache/jcache/JCacheXKMSClientCache.java
index 8c8921efaa9..fa029a96402 100644
--- 
a/services/xkms/xkms-client/src/main/java/org/apache/cxf/xkms/cache/jcache/JCacheXKMSClientCache.java
+++ 
b/services/xkms/xkms-client/src/main/java/org/apache/cxf/xkms/cache/jcache/JCacheXKMSClientCache.java
@@ -33,6 +33,7 @@ import org.apache.cxf.Bus;
 import org.apache.cxf.BusFactory;
 import org.apache.cxf.buslifecycle.BusLifeCycleListener;
 import org.apache.cxf.buslifecycle.BusLifeCycleManager;
+import org.apache.cxf.rt.security.utils.JCacheUtils;
 import org.apache.cxf.ws.security.utils.JCacheSupport;
 import org.apache.cxf.xkms.cache.XKMSCacheToken;
 import org.apache.cxf.xkms.cache.XKMSClientCache;
@@ -43,9 +44,8 @@ import org.apache.cxf.xkms.cache.XKMSClientCacheException;
  */
 public class JCacheXKMSClientCache implements XKMSClientCache, 
BusLifeCycleListener {
     private final Cache<String, XKMSCacheToken> cache;
-    private final CacheManager cacheManager;
     private final Bus bus;
-    private final String cacheKey;
+    private boolean closed;
 
     public JCacheXKMSClientCache() throws XKMSClientCacheException {
         this(null);
@@ -60,10 +60,10 @@ public class JCacheXKMSClientCache implements 
XKMSClientCache, BusLifeCycleListe
         }
 
         this.bus = cxfBus;
-        this.cacheKey = UUID.randomUUID().toString();
+        String cacheKey = UUID.randomUUID().toString();
 
         final CachingProvider cachingProvider = Caching.getCachingProvider();
-        cacheManager = cachingProvider.getCacheManager(); 
+        final CacheManager cacheManager = cachingProvider.getCacheManager();
 
         cache = JCacheSupport.getOrCreate(cacheManager, cacheKey, 
String.class, XKMSCacheToken.class,
             cacheConfiguration -> cacheConfiguration.setExpiryPolicyFactory(() 
-> new ExpiryPolicy() {
@@ -101,9 +101,11 @@ public class JCacheXKMSClientCache implements 
XKMSClientCache, BusLifeCycleListe
     }
 
     public synchronized void close() {
-        if (!cacheManager.isClosed()) {
-            cacheManager.destroyCache(cacheKey);
-            cacheManager.close();
+        // the cache is in the provider's default manager, which other caches 
(such as the WS-Security
+        // replay caches) share, so only the cache is released
+        if (!closed) {
+            closed = true;
+            JCacheUtils.release(cache);
 
             if (bus != null) {
                 
bus.getExtension(BusLifeCycleManager.class).unregisterLifeCycleListener(this);
diff --git 
a/services/xkms/xkms-client/src/test/java/org/apache/cxf/xkms/cache/jcache/JCacheXKMSClientCacheLifecycleTest.java
 
b/services/xkms/xkms-client/src/test/java/org/apache/cxf/xkms/cache/jcache/JCacheXKMSClientCacheLifecycleTest.java
new file mode 100644
index 00000000000..84e107c7349
--- /dev/null
+++ 
b/services/xkms/xkms-client/src/test/java/org/apache/cxf/xkms/cache/jcache/JCacheXKMSClientCacheLifecycleTest.java
@@ -0,0 +1,54 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.cxf.xkms.cache.jcache;
+
+import java.util.UUID;
+
+import javax.cache.Cache;
+import javax.cache.CacheManager;
+import javax.cache.Caching;
+import javax.cache.configuration.MutableConfiguration;
+
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+
+public class JCacheXKMSClientCacheLifecycleTest {
+
+    // The XKMS cache is in the provider's default manager, which other caches 
share, so closing it keeps
+    // the manager and their caches open
+    @Test
+    public void testCloseLeavesDefaultManagerOpen() throws Exception {
+        CacheManager manager = Caching.getCachingProvider().getCacheManager();
+        String name = "other-" + UUID.randomUUID();
+        Cache<String, String> other =
+            manager.createCache(name, new MutableConfiguration<String, 
String>().setTypes(String.class, String.class));
+        try {
+            JCacheXKMSClientCache xkmsCache = new JCacheXKMSClientCache();
+            xkmsCache.close();
+            xkmsCache.close();
+            assertFalse(manager.isClosed());
+            other.put("key", "value");
+            assertEquals("value", other.get("key"));
+        } finally {
+            manager.destroyCache(name);
+        }
+    }
+}

Reply via email to