diff --git a/.github/workflows/main-ci.yml b/.github/workflows/main-ci.yml
index b23e0b36..69c83ce9 100644
--- a/.github/workflows/main-ci.yml
+++ b/.github/workflows/main-ci.yml
@@ -10,6 +10,20 @@ jobs:
verify:
runs-on: ubuntu-latest
timeout-minutes: 30
+ services:
+ redis:
+ image: redis:8.4.0
+ ports:
+ - 6379/tcp
+ options: >-
+ --health-cmd "redis-cli ping"
+ --health-interval 5s
+ --health-timeout 3s
+ --health-retries 5
+ memcached:
+ image: memcached:1.6.45-alpine
+ ports:
+ - 11211/tcp
steps:
- uses: actions/checkout@v7
- uses: actions/setup-java@v5
@@ -20,18 +34,155 @@ jobs:
uses: actions/checkout@v7
with:
repository: easy-4-java/jwt-issuer
- ref: 6b1a4de65a12a155e98e957ea82e446ef6420b36
+ ref: c6edbf6a56a0c8ae6409b9fc1b0ef9639c4063d1
path: .ci-dependencies/jwt-issuer
- name: Verify and install JWT issuer
run: mvn -B -ntp -s .github/maven-central-settings.xml -Dmaven.repo.local="${RUNNER_TEMP}/verified-m2" -f .ci-dependencies/jwt-issuer/pom.xml clean install
- name: Verify Shiro extension
- run: mvn -B -ntp -s .github/maven-central-settings.xml -Dmaven.repo.local="${RUNNER_TEMP}/verified-m2" clean verify
+ env:
+ RETRY_REDIS_CONTAINER: ${{ job.services.redis.id }}
+ RETRY_REDIS_PORT: ${{ job.services.redis.ports['6379'] }}
+ RETRY_MEMCACHED_PORT: ${{ job.services.memcached.ports['11211'] }}
+ shell: bash
+ run: |
+ set -euo pipefail
+ auth_file=$(mktemp "${RUNNER_TEMP}/memcached-auth.XXXXXX")
+ auth_container=
+ binary_container=
+ warm_container=
+ cleanup() {
+ if [[ -n "$auth_container" ]]; then
+ docker rm -f "$auth_container" >/dev/null
+ fi
+ if [[ -n "$binary_container" ]]; then
+ docker rm -f "$binary_container" >/dev/null
+ fi
+ if [[ -n "$warm_container" ]]; then
+ docker rm -f "$warm_container" >/dev/null
+ fi
+ rm -f "$auth_file"
+ }
+ trap cleanup EXIT
+ # Local CI fixture only. The container reads this as its non-root user.
+ printf '%s\n' 'fixture-user:fixture-password' > "$auth_file"
+ chmod 0644 "$auth_file"
+ auth_container=$(docker run -d --publish 127.0.0.1::11211/tcp \
+ --mount "type=bind,src=$auth_file,dst=/memcached-auth,readonly" \
+ memcached:1.6.45-alpine memcached -U 0 -Y /memcached-auth)
+ binary_container=$(docker run -d --publish 127.0.0.1::11211/tcp \
+ memcached:1.6.45-alpine memcached -U 0 -B binary)
+ warm_container=$(docker run -d --user 0 --publish 127.0.0.1::11211/tcp \
+ --mount "type=bind,src=$auth_file,dst=/memcached-auth,readonly" \
+ --tmpfs /state:rw,size=96m memcached:1.6.45-alpine sh -ec '
+ chown memcache /state
+ mkdir -p /etc/sasl2
+ printf "%s\n" "mech_list: plain" >/etc/sasl2/memcached.conf
+ sed "s/:/@$(hostname):/" /memcached-auth >/state/sasl-auth
+ chown memcache /state/sasl-auth
+ chmod 0600 /state/sasl-auth
+ MEMCACHED_SASL_PWDB=/state/sasl-auth memcached -u memcache -U 0 -m 64 -S -e /state/memory &
+ child=$!
+ echo "$child" >/state/source.pid
+ wait "$child"
+ # The server requires the clock to advance beyond the saved stop second.
+ sleep 2
+ exec memcached -u memcache -U 0 -m 64 -Y /memcached-auth -e /state/memory
+ ')
+ ready_port() {
+ local container=$1 binding port
+ binding=$(docker port "$container" 11211/tcp)
+ port=${binding##*:}
+ [[ "$port" =~ ^[0-9]+$ ]] || return 1
+ for _ in {1..40}; do
+ if (: < "/dev/tcp/127.0.0.1/$port") 2>/dev/null; then
+ printf '%s\n' "$port"
+ return
+ fi
+ sleep 0.25
+ done
+ docker logs "$container" >&2
+ return 1
+ }
+ auth_port=$(ready_port "$auth_container")
+ binary_port=$(ready_port "$binary_container")
+ warm_port=$(ready_port "$warm_container")
+ mvn -B -ntp -s .github/maven-central-settings.xml -Dmaven.repo.local="${RUNNER_TEMP}/verified-m2" \
+ -Dshiro.redis.test.container="$RETRY_REDIS_CONTAINER" -Dshiro.redis.test.port="$RETRY_REDIS_PORT" \
+ -Dshiro.memcached.test.port="$RETRY_MEMCACHED_PORT" -Dshiro.memcached.auth.test.port="$auth_port" \
+ -Dshiro.memcached.binary.test.port="$binary_port" -Dshiro.memcached.warm.test.port="$warm_port" \
+ -Dshiro.memcached.warm.test.container="$warm_container" clean verify
+ python3 - <<'PYTHON'
+ from pathlib import Path
+ from xml.etree import ElementTree
+
+ reports = Path("shiro-extension-core/target/surefire-reports")
+ suite = ElementTree.parse(next(reports.glob("TEST-*J2CacheMemcachedCredentialRetryStoreIntegrationTest.xml")))
+ for name in (
+ "importsThroughAnAuthenticatedMetaConnectionWithItsOriginalDeadline",
+ "refusesToImportWhenOnlyTheBinaryProtocolCanReadTheCounter",
+ "importsAuthoritativeSnapshotWithTheOriginalServerDeadline",
+ "importsLegacyWindowsAfterSaslSourceWarmRestart",
+ ):
+ case = suite.find(f'./testcase[@name="{name}"]')
+ if case is None or any(case.find(status) is not None for status in ("failure", "error", "skipped")):
+ raise SystemExit(f"Expected an executed, successful Memcached test: {name}")
+ PYTHON
+ - name: Verify J2Cache and Redisson retry migration on Redis Cluster
+ shell: bash
+ run: |
+ set -euo pipefail
+ containers=()
+ trap 'if (( ${#containers[@]} > 0 )); then docker rm -f "${containers[@]}" >/dev/null; fi' EXIT
+ nodes=()
+ for port in 16380 16381 16382; do
+ container=$(docker run -d --rm --network host redis:8.4.0 redis-server \
+ --bind 127.0.0.1 --port "$port" --cluster-enabled yes \
+ --cluster-announce-ip 127.0.0.1 --cluster-config-file nodes.conf \
+ --save '' --appendonly no)
+ containers+=("$container")
+ nodes+=("127.0.0.1:$port")
+ for attempt in {1..60}; do
+ if docker exec "$container" redis-cli -p "$port" ping | grep -qx PONG; then
+ break
+ fi
+ if (( attempt == 60 )); then
+ docker logs "$container"
+ exit 1
+ fi
+ sleep 0.25
+ done
+ done
+ timeout 30s docker exec "${containers[0]}" redis-cli --cluster create "${nodes[@]}" --cluster-replicas 0 --cluster-yes
+ cluster_nodes=$(IFS=,; printf '%s' "${nodes[*]}")
+ mvn -B -ntp -s .github/maven-central-settings.xml -Dmaven.repo.local="${RUNNER_TEMP}/verified-m2" \
+ -pl shiro-extension-core -Dshiro.redis.test.cluster.nodes="$cluster_nodes" \
+ '-Dtest=J2CacheRedisClusterMigrationTest,RedissonCredentialRetryStoreIntegrationTest#migratesTheLegacyMapEntryWithoutRefreshingItsIdleDeadline+keepsMapExpiryAndImportsPersistentZeroCounts' test
+ mvn -B -ntp -s .github/maven-central-settings.xml -Dmaven.repo.local="${RUNNER_TEMP}/verified-m2" \
+ -pl shiro-extension-core -Dshiro.redis.test.cluster.nodes="$cluster_nodes" \
+ -Dshiro.test.fileEncoding=ISO-8859-1 -Dshiro.redis.test.expectedCharset=ISO-8859-1 \
+ -Dsurefire.reportNameSuffix=latin1 -Dtest=J2CacheRedisClusterMigrationTest test
+ python3 - <<'PYTHON'
+ from pathlib import Path
+ from xml.etree import ElementTree
+
+ report = Path("shiro-extension-core/target/surefire-reports")
+ for name in ("J2CacheRedisClusterMigrationTest", "J2CacheRedisClusterMigrationTest-latin1", "RedissonCredentialRetryStoreIntegrationTest"):
+ suite = ElementTree.parse(next(report.glob(f"TEST-*{name}.xml"))).getroot()
+ if tuple(suite.get(key) for key in ("tests", "failures", "errors", "skipped")) != ("2", "0", "0", "0"):
+ raise SystemExit(f"Expected two Redis Cluster migration tests without skips in {name}")
+ PYTHON
- name: Require coverage for modules with existing tests
run: |
test -s .ci-dependencies/jwt-issuer/jwt-issuer-with-jjwt/target/jacoco.exec
test -s .ci-dependencies/jwt-issuer/jwt-issuer-with-jjwt/target/site/jacoco/jacoco.xml
test -s shiro-extension-core/target/jacoco.exec
test -s shiro-extension-core/target/site/jacoco/jacoco.xml
+ test -s shiro-extension-spring/target/jacoco.exec
+ test -s shiro-extension-spring/target/site/jacoco/jacoco.xml
+ test -s shiro-extension-hazelcast3/target/jacoco.exec
+ test -s shiro-extension-hazelcast3/target/site/jacoco/jacoco.xml
+ test -s shiro-extension-spring-redis4/target/jacoco.exec
+ test -s shiro-extension-spring-redis4/target/site/jacoco/jacoco.xml
- uses: actions/upload-artifact@v7
if: always()
with:
diff --git a/README.md b/README.md
index 294a0f47..972d9b41 100644
--- a/README.md
+++ b/README.md
@@ -184,7 +184,7 @@ realm.setCredentialsMatcher(new DefaultCredentialsMatcher());
## 7. Configuration
-This is a library: there are no configuration properties or prefixes. Behavior is configured through constructor/bean injection:
+Configure behavior through constructors and beans.
| Extension point | Configurable via |
| :--- | :--- |
@@ -194,6 +194,37 @@ This is a library: there are no configuration properties or prefixes. Behavior i
| Filters (`HttpServletShiroFilter` and friends) | bean properties and the Shiro filter-chain definition |
| i18n messages | bundled `org/apache/shiro/biz/messages*.properties`, `ShiroBizMessageSource` |
+### Shared credential retry state in Spring Boot
+
+For a Spring-managed retry matcher with cache name `login`, declare a provider-backed `CredentialRetryStore` bean named `shiro.credential-retry.login`. Spring Boot binds it to `DefaultCredentialsMatcher` and `CredentialsRetryLimitCredentialsMatcher`, including instances held by Spring-managed realms. An explicitly assigned store takes precedence. Matchers without a matching bean keep their Shiro cache configuration. Use the same provider, retry namespace and principal key mapping across the instances that share the window.
+
+For an existing Ehcache 2 retry cache, stop all legacy clients of that region before enabling the shared store. Reuse the same region and principal keys. The first reservation upgrades the stored legacy counter under the key lock, counts the current attempt and keeps the original TTL deadline and the configured time-to-idle policy. Use a strongly consistent region when clustered.
+
+For native Ehcache 3, pause all retry clients, drain writes, and use exactly one migration writer per region. Call `migrateLegacyWindow` for each known principal using the original cache. The region must use creation-only or eternal expiry. A region that accepts both legacy counters and retry windows, such as `Serializable`, stores attempts directly. An `AtomicInteger`-typed region stores a serializable counter subtype holding the window ID and must preserve that subtype. Live entries are replaced in place while retaining the existing deadline.
+
+For legacy regions using a verified finite TTL or TTI that renews on updates or reads, use a bounded drain for cutover. Pause all clients and background jobs that can access the retry region, and wait until in-flight operations finish. From that point, wait at least the longest configured lifetime across the source regions, including any clock margin required by the deployment. Enable the new store on a separate region only after that interval, with its configured creation window. The old region is left intact and its counters expire on their own. This path requires a maintenance pause and explicit acceptance of the new region’s fixed-window policy. Eternal entries, custom policies with unknown upper bounds, and deployments that must retain renewal behavior require a different path.
+
+For rollback, keep retry clients paused and drain outstanding writes before calling `restoreLegacyWindow` for each known principal. The cache must accept `AtomicInteger`. A live retry window becomes a plain legacy counter with its current count and original deadline. Missing, expired, and already restored entries are skipped.
+
+For Hazelcast 5.2+ and 3.12, use the same cutover steps for the dedicated retry IMap. Deploy the retry-store module to every member and reuse the original map and principal keys. The first reservation converts the legacy counter atomically, retaining its remaining TTL and refreshing idle time under the existing policy. For the 3.12 adapter, supply the map's configured max idle explicitly.
+
+For an existing JCache retry region, stop legacy clients and reuse the region and principal keys. The JCache entry processor converts the saved counter and reserves the current attempt in one update. The region must use store-by-value and retain its creation deadline on access and update. A region that accepts both value types, for example with value type `Object`, stores retry windows directly. A region typed as `AtomicInteger` stores a serializable counter subtype holding the window ID. Verify that the provider and its configured serializer retain the subtype and deploy this module to every executing member before cutover. Typed migration was verified on a two-member Hazelcast JCache cluster. For rollback, pause all retry clients, drain outstanding writes, and call `restoreLegacyWindow` for every converted principal in the original region. It restores a plain `AtomicInteger` with the current count and original deadline. It skips missing, expired, and restored entries. Check for any remaining converted entries before resuming legacy clients.
+
+For Spring Data Redis, pause all old and new retry clients and wait for outstanding cache writes to reach Redis before importing. Call the adapter’s `migrateLegacyWindow` for each known string principal with the original cache and the distinct destination namespace used by the new store. The import copies the saved count and absolute Redis expiry using the source cache’s key and value serializers. It leaves source entries intact and skips missing, expired, and occupied destinations. Reconcile the submitted principals before resuming clients and finish all imports during the same cutover. If the new policy uses time-to-idle, it applies on the next reservation.
+
+The J2Cache Jedis and Lettuce adapters also expose `migrateLegacyWindow` for each known string principal during an exclusive cutover. Import reads the saved L2 counter using the channel’s serializer, preserves the Redis deadline for generic keys or the hash region, and creates only absent destination windows. Keep the original provider configuration and use a distinct destination namespace. For legacy keys that use the JVM default charset, run migration with the charset that wrote the source region. Jedis routes the expiry lookup using the original binary key. For non-UTF-8 Lettuce keys, supply a binary scripting connection in addition to the UTF-8 destination connection.
+
+The J2Cache Memcached adapter can import a known principal during the same exclusive cutover. Select the source server using the original key routing. On a trusted source that accepts the Meta Text protocol, pass its address to `migrateLegacyWindow`. For authenticated access, first authenticate a dedicated Meta Text connection, configure a finite socket read timeout, and pass it to `migrateLegacyWindowFromMetaConnection`. The caller manages authentication, transport security, and closure of that connection. It must have no outstanding commands and be used by one reader at a time. The adapter reads the value with its remaining TTL, determines the absolute deadline at server-second precision, retains the original entry, and creates the destination only if it is absent. A binary-only source, including one that requires binary SASL, requires a separate migration path because its get operation does not report the existing TTL. For windows with a verified finite TTL bound, pause and drain all retry clients, then wait for the maximum remaining lifetime across the source nodes before enabling the new store. For persistent windows or unknown TTL bounds, keep using the legacy store until you can obtain an authoritative expiry snapshot. Binary GET returns the counter and CAS, which cannot distinguish a finite window from a persistent one.
+
+During the exclusive cutover, pass a verified count and its original absolute Unix deadline from the same source entry to `migrateLegacyWindowFromSnapshot`. Use zero only for a confirmed persistent entry. Import while clients are paused and writes are drained. Expired snapshots and attempts to overwrite existing destination windows return false.
+
+During the same exclusive cutover, the overload of `migrateLegacyWindowFromSnapshot` that accepts a source client and a nonzero CAS also checks the live entry version and decoded count. It returns false if the source is missing, the version or count changed, the deadline passed, or the destination already has a window. The caller must connect to the original source process with the same routing and record the CAS, count and authoritative deadline together. The binary protocol provides the entry version and value. The deadline still comes from the trusted snapshot.
+
+If the binary-only source already runs with [Memcached warm restart](https://docs.memcached.org/features/restart/) enabled on a retained RAM-backed memory file, it can expose the restored windows to the existing Meta Text importer during the exclusive cutover. Keep clients paused and writes drained. Gracefully stop the source with `SIGUSR1`, wait until the host clock advances beyond the saved stop second, and restart it from the same memory file with compatible slab and CAS settings and an isolated Meta Text listener. Keep the listener authenticated or restricted to trusted local access. Verify that the source actually recovered its items before importing. A loopback Memcached 1.6.45 fixture wrote the legacy counters using binary SASL, then imported the recovered windows over authenticated Meta Text. The finite window retained its exact original deadline, and the persistent window remained without a deadline. A third window that expired during the restart stayed absent. This route requires warm restart to have been enabled before the legacy windows were written.
+
+
+For a retry cache stored in a Redisson 3.12.5 `RMapCache`, pass the original cache and principal to `migrateLegacyWindow` during the same exclusive cutover. The adapter copies the count, entry lifetime, idle policy and current idle deadline without refreshing the source. It also honors a shorter map-wide expiry. Use a distinct destination namespace on the same Redis deployment.
+
## 8. Core Usage / API
Selected public API (all classes under `org.apache.shiro.biz`):
diff --git a/README.zh-CN.md b/README.zh-CN.md
index ed346754..e764b1de 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -184,7 +184,7 @@ realm.setCredentialsMatcher(new DefaultCredentialsMatcher());
## 7. Configuration
-这是库:没有配置属性与属性前缀。行为通过构造器/Bean 注入配置:
+通过构造器和 Bean 配置扩展行为。
| 扩展点 | 配置方式 |
| :--- | :--- |
@@ -194,6 +194,37 @@ realm.setCredentialsMatcher(new DefaultCredentialsMatcher());
| 过滤器(`HttpServletShiroFilter` 等) | Bean 属性与 Shiro 过滤器链定义 |
| i18n 消息 | 随包 `org/apache/shiro/biz/messages*.properties`、`ShiroBizMessageSource` |
+### Spring Boot 共享重试计数
+
+如果匹配器的重试缓存名为 `login`,声明名为 `shiro.credential-retry.login` 的 `CredentialRetryStore` Bean。Spring Boot 会将它绑定到 `DefaultCredentialsMatcher` 和 `CredentialsRetryLimitCredentialsMatcher`,包括 Spring 管理的 Realm 内部创建的实例。手工指定的存储优先。缺少同名 Bean 时,匹配器沿用原 Shiro 缓存配置。共享重试窗口的应用实例应使用相同的缓存提供者、重试命名空间和主体键映射。
+
+对于现有 Ehcache 2 重试缓存,先停止访问该区域的全部旧版客户端,再启用共享重试存储,并沿用原区域及主体键。首次预留在键锁内转换已保存的旧计数,计入本次尝试,并保留原 TTL 截止时间和配置的空闲过期策略。集群部署使用强一致性区域。
+
+对于原生 Ehcache 3,暂停所有重试客户端并排空在途写入,每个区域只允许一个迁移写入方。使用原缓存对已知主体调用 `migrateLegacyWindow`。区域须使用仅在创建时设置的过期策略或永不过期策略。`Serializable` 等可接受旧计数和新窗口的区域直接保存新窗口。`AtomicInteger` 类型区域保存含窗口 ID 的可序列化子类型,要求序列化器保留该类型。活跃条目在原位置替换,保留原截止时间。
+
+旧区域的 TTL 或 TTI 若会因写入或访问续期,且能确认有限上界,可在维护窗口内排空切换。暂停所有可能访问旧重试区域的客户端和后台任务,等在途操作全部完成。从该时点起,至少等待所有来源区域配置中最长的一段有效期,并计入部署所需的时钟余量。等待结束后,在独立区域启用新存储并配置创建窗口。旧区域保持原状,已有计数按自身策略自然到期。该路径需要维护停顿,并确认新区域采用固定窗口。存在永不过期条目、无法证明上界的自定义策略,或必须继续保留续期行为时,需另选切换方式。
+
+回滚时保持客户端暂停并排空在途写入,再对已知主体调用 `restoreLegacyWindow`。缓存区域必须接受 `AtomicInteger`。活跃窗口恢复为普通旧版计数,保留当前次数和原截止时间。缺失、已过期或已经恢复的条目会跳过。
+
+Hazelcast 5.2+ 与 3.12 的独立重试 IMap 沿用同样的切换顺序。所有集群成员须部署重试存储模块,并沿用原 IMap 和主体键。首次预留会原子转换旧计数,保留剩余 TTL,并按原策略刷新空闲时间。使用 3.12 适配器时需传入 IMap 配置的最大空闲时长。
+
+对于现有 JCache 重试区域,停止旧客户端后沿用原区域和主体键。条目处理器会在同一次更新中转换计数并预留本次尝试。区域必须按值存储,并在访问和更新时保留原截止时间。值类型允许两种格式的区域(例如 `Object`)直接存储重试窗口。值类型为 `AtomicInteger` 的区域使用可序列化的计数器子类保存窗口标识。切换前验证提供方及其序列化配置能保留子类,并在所有执行节点部署此模块。该类型区域的迁移已在双节点 Hazelcast JCache 集群验证。回切时暂停所有重试客户端,等待在途写入完成,然后对原区域内每个已转换的主体调用 `restoreLegacyWindow`。该方法原地恢复普通 `AtomicInteger`,保留当前计数和原截止时间,跳过缺失、过期或已恢复条目。检查区域中是否仍有已转换条目,再恢复旧客户端。
+
+对于 Spring Data Redis,切换期间暂停所有旧版和新版重试客户端,等在途缓存写入全部到达 Redis 后再导入。用原缓存和新存储使用的独立目标命名空间,对每个已知的字符串主体调用适配器的 `migrateLegacyWindow`。导入沿用源缓存的键和值序列化配置,复制已保存的计数与 Redis 绝对截止时间。源数据保留,跳过缺失、已过期和目标已存在的窗口。恢复客户端之前先核对本次提交的全部主体,并在同一切换窗口完成导入。启用空闲续期时,从下一次预留起应用原策略。
+
+J2Cache 的 Jedis 和 Lettuce 适配器也可在独占切换期间对已知字符串主体调用 `migrateLegacyWindow`。导入按原渠道的序列化方式读取 Redis 二级缓存计数,保留普通键或 Hash 区域的 Redis 截止时间,仅在目标窗口不存在时写入。沿用原缓存提供者配置,并指定独立的目标命名空间。迁移按 JVM 默认字符集写入的旧键时,沿用原字符集。Jedis 按原二进制键查询截止时间。对于非 UTF-8 的 Lettuce 旧键,除 UTF-8 目标连接外,还需传入二进制脚本连接。
+
+J2Cache Memcached 适配器也可在同一独占切换阶段导入已知主体。按原键路由选择保存旧值的源节点。对允许 Meta Text 协议的可信源节点,可向 `migrateLegacyWindow` 传入地址。需要认证时,先认证专用 Meta Text 连接,设置有限的读取超时,再传给 `migrateLegacyWindowFromMetaConnection`。调用方负责认证、传输安全和关闭连接。连接上应没有在途命令,并由单个调用方顺序读取。适配器同时读取旧值和剩余有效期,按服务端秒级精度确定绝对截止时间,保留原条目,仅在目标不存在时写入。仅支持二进制协议的节点(包括要求二进制 SASL 的节点)仍需要独立迁移方式,因为其 GET 操作不返回原有效期。 如果能确认所有旧窗口的有效期上限,先暂停旧、新客户端并排空在途写入,等待所有源节点上的旧窗口过期,再启用新存储。存在永久窗口或无法确认有效期上限时,应继续使用旧存储,直到取得可信的到期时间快照。二进制 GET 返回计数和 CAS,无法区分限时窗口和永久窗口。
+
+独占切换期间可调用 `migrateLegacyWindowFromSnapshot`。先暂停重试客户端并排空在途写入,再传入同一源条目的可信计数和原始 Unix 秒截止时间。只有已确认永久有效的条目才传 0。已过期或目标窗口已存在时返回 false。
+
+独占切换期间也可使用接收源客户端和非零 CAS 的 `migrateLegacyWindowFromSnapshot` 重载。它会核对源条目当前的版本和解码后的计数。源条目消失、版本或计数不匹配、已过期或目标窗口已存在时返回 false。源客户端须采用原路由并连接原进程。采集时须记录同一条目的 CAS、计数和可信截止时间。二进制协议可核对版本和值,截止时间仍来自可信快照。
+
+如果仅支持二进制协议的源节点已在可保留的内存文件上启用 [Memcached 热重启](https://docs.memcached.org/features/restart/),可在独占切换期间通过现有 Meta Text 导入器读取恢复后的窗口。保持客户端暂停并排空在途写入。向源进程发送 `SIGUSR1` 以正常停机,等待主机时钟超过记录的停机秒数,再使用同一个内存文件和兼容的 slab、CAS 设置重启,并开放隔离的 Meta Text 监听。监听应启用认证或限制为可信本机访问。确认源条目确实恢复后再导入。Memcached 1.6.45 回环测试使用二进制 SASL 写入旧计数,热重启后通过已认证的 Meta Text 连接导入。限时窗口保留原始截止时间,永久窗口仍无截止时间,停机期间过期的窗口仍然缺失。此方式要求在写入旧窗口前已启用热重启。
+
+
+对于 Redisson 3.12.5 的 `RMapCache` 重试区域,在同一独占切换阶段使用原缓存和主体调用 `migrateLegacyWindow`。导入复制原计数、条目固定截止时间、空闲策略和当前空闲截止时间,读取时不延长源窗口。若整个 Map 更早过期,使用更早的截止时间。同一 Redis 部署内使用独立的目标命名空间。
+
## 8. Core Usage / API
精选公开 API(类均位于 `org.apache.shiro.biz` 包下):
diff --git a/pom.xml b/pom.xml
index a9162619..f23a7ab0 100644
--- a/pom.xml
+++ b/pom.xml
@@ -192,7 +192,7 @@
false
once
@{jacocoArgLine} -Xmx1024m
- -Dfile.encoding=UTF-8
+ -Dfile.encoding=${shiro.test.fileEncoding}
${basedir}/target/test-classes
@@ -487,6 +487,7 @@
2.0.x.20260630-SNAPSHOT
UTF-8
+ UTF-8
2.9.3
1.22.0
3.20.0
@@ -643,6 +644,8 @@
shiro-extension-core
+ shiro-extension-hazelcast3
shiro-extension-spring
+ shiro-extension-spring-redis4
diff --git a/shiro-extension-core/pom.xml b/shiro-extension-core/pom.xml
index a41b6009..3addefc3 100644
--- a/shiro-extension-core/pom.xml
+++ b/shiro-extension-core/pom.xml
@@ -74,6 +74,54 @@
lombok
provided
+
+ net.sf.ehcache
+ ehcache-core
+ 2.6.11
+ provided
+
+
+ org.ehcache
+ ehcache
+ 3.6.0
+ provided
+
+
+ javax.cache
+ cache-api
+ 1.1.1
+ provided
+
+
+ net.oschina.j2cache
+ j2cache-core
+ 2.8.5-release
+ provided
+
+
+ com.googlecode.xmemcached
+ xmemcached
+ 2.4.5
+ provided
+
+
+ io.lettuce
+ lettuce-core
+ 5.3.7.RELEASE
+ provided
+
+
+ org.redisson
+ redisson
+ 3.12.5
+ provided
+
+
+ com.hazelcast
+ hazelcast
+ 5.3.7
+ provided
+
junit
junit
diff --git a/shiro-extension-core/src/main/java/org/apache/shiro/biz/authc/credential/CredentialRetryStore.java b/shiro-extension-core/src/main/java/org/apache/shiro/biz/authc/credential/CredentialRetryStore.java
new file mode 100644
index 00000000..248550a9
--- /dev/null
+++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/authc/credential/CredentialRetryStore.java
@@ -0,0 +1,54 @@
+package org.apache.shiro.biz.authc.credential;
+
+import java.io.Serializable;
+import java.util.Objects;
+import lombok.EqualsAndHashCode;
+import lombok.Getter;
+
+/**
+ * Shared credential retry state for one configured retry cache namespace.
+ * Implementations use the cache provider's atomic operations and expiration policy.
+ */
+public interface CredentialRetryStore {
+
+ /**
+ * Atomically starts or increments the current window for a principal. Creation uses
+ * the configured expiration policy and an independent window identifier. Incrementing
+ * an existing window preserves its expiration and saturates at {@link Integer#MAX_VALUE}.
+ *
+ * @param principal stable key for the principal in this cache namespace
+ * @return the window identifier and count after reserving this attempt
+ */
+ Attempt reserve(Object principal);
+
+ /**
+ * Atomically clears the principal's window if it still has the specified identifier.
+ *
+ * @param principal stable key for the principal in this cache namespace
+ * @param windowId identifier returned by the attempt reservation
+ */
+ void clearIfCurrent(Object principal, String windowId);
+
+ /** Data returned by a successful reservation. */
+ @Getter
+ @EqualsAndHashCode
+ final class Attempt implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ private final String windowId;
+ private final int count;
+
+ /**
+ * @param windowId identifier unique to this principal's retry window
+ * @param count attempt count after the reservation, starting at one
+ */
+ public Attempt(String windowId, int count) {
+ this.windowId = Objects.requireNonNull(windowId, "windowId");
+ if (count < 1) {
+ throw new IllegalArgumentException("Attempt count must be positive");
+ }
+ this.count = count;
+ }
+ }
+}
diff --git a/shiro-extension-core/src/main/java/org/apache/shiro/biz/authc/credential/CredentialRetrySupport.java b/shiro-extension-core/src/main/java/org/apache/shiro/biz/authc/credential/CredentialRetrySupport.java
new file mode 100644
index 00000000..4c469a46
--- /dev/null
+++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/authc/credential/CredentialRetrySupport.java
@@ -0,0 +1,22 @@
+package org.apache.shiro.biz.authc.credential;
+
+import java.util.function.BooleanSupplier;
+import org.apache.shiro.authc.ExcessiveAttemptsException;
+
+final class CredentialRetrySupport {
+
+ private CredentialRetrySupport() {
+ }
+
+ static boolean match(CredentialRetryStore store, Object principal, int limit, BooleanSupplier credentialsMatch) {
+ CredentialRetryStore.Attempt attempt = store.reserve(principal);
+ if (attempt.getCount() >= limit) {
+ throw new ExcessiveAttemptsException();
+ }
+ boolean matches = credentialsMatch.getAsBoolean();
+ if (matches) {
+ store.clearIfCurrent(principal, attempt.getWindowId());
+ }
+ return matches;
+ }
+}
diff --git a/shiro-extension-core/src/main/java/org/apache/shiro/biz/authc/credential/CredentialsRetryLimitCredentialsMatcher.java b/shiro-extension-core/src/main/java/org/apache/shiro/biz/authc/credential/CredentialsRetryLimitCredentialsMatcher.java
index 5645a1b3..952080b8 100644
--- a/shiro-extension-core/src/main/java/org/apache/shiro/biz/authc/credential/CredentialsRetryLimitCredentialsMatcher.java
+++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/authc/credential/CredentialsRetryLimitCredentialsMatcher.java
@@ -22,6 +22,7 @@
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
+import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
/**
@@ -54,8 +55,32 @@ public class CredentialsRetryLimitCredentialsMatcher extends HashedCredentialsMa
*/
protected String credentialsRetryCacheName = CREDENTIALS_RETRY_CACHE_NAME;
+ private volatile CredentialRetryStore credentialRetryStore;
+
+ /**
+ * Configures atomic retry accounting for this matcher's retry cache namespace.
+ *
+ * @param store provider-backed store, or null to use the existing Shiro cache integration
+ */
+ public void setCredentialRetryStore(CredentialRetryStore store) {
+ this.credentialRetryStore = store;
+ }
+
+ /**
+ * @return the configured retry store, or null when using the Shiro retry cache
+ */
+ public CredentialRetryStore getCredentialRetryStore() {
+ return credentialRetryStore;
+ }
+
@Override
public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
+ CredentialRetryStore store = credentialRetryStore;
+ if (Objects.nonNull(store)) {
+ return CredentialRetrySupport.match(store, token.getPrincipal(), getCredentialsRetryTimesLimit(),
+ () -> super.doCredentialsMatch(token, info));
+ }
+
AtomicInteger retryCount = getCachedRetryTimes(token.getPrincipal());
if (retryCount == null) {
@@ -109,11 +134,11 @@ public void setCredentialsRetryCacheName(String credentialsRetryCacheName) {
this.credentialsRetryCacheName = credentialsRetryCacheName;
}
- public void setCredentialsRetryTimes(Cache
+
+ org.springframework.boot
+ spring-boot-autoconfigure
+ 2.7.18
+ provided
+
+
+ org.springframework.data
+ spring-data-redis
+ 2.7.18
+ provided
+
+
+ javax.cache
+ cache-api
+ 1.1.1
+ provided
+
+
+ io.lettuce
+ lettuce-core
+ 6.1.10.RELEASE
+ test
+
+
+ org.springframework
+ spring-context-support
+ ${spring.version}
+ provided
+
+
+ com.hazelcast
+ hazelcast
+ 5.3.7
+ test
+
+
+ junit
+ junit
+ test
+
diff --git a/shiro-extension-spring/src/main/java/org/apache/shiro/biz/authc/credential/spring/CredentialRetryStoreAutoConfiguration.java b/shiro-extension-spring/src/main/java/org/apache/shiro/biz/authc/credential/spring/CredentialRetryStoreAutoConfiguration.java
new file mode 100644
index 00000000..5c59ade7
--- /dev/null
+++ b/shiro-extension-spring/src/main/java/org/apache/shiro/biz/authc/credential/spring/CredentialRetryStoreAutoConfiguration.java
@@ -0,0 +1,70 @@
+package org.apache.shiro.biz.authc.credential.spring;
+
+import java.util.Objects;
+import java.util.function.Consumer;
+import org.apache.shiro.biz.authc.credential.CredentialRetryStore;
+import org.apache.shiro.biz.authc.credential.CredentialsRetryLimitCredentialsMatcher;
+import org.apache.shiro.biz.authc.credential.DefaultCredentialsMatcher;
+import org.apache.shiro.realm.AuthenticatingRealm;
+import org.springframework.beans.factory.BeanFactory;
+import org.springframework.beans.factory.config.BeanDefinition;
+import org.springframework.beans.factory.config.BeanPostProcessor;
+import org.springframework.boot.autoconfigure.AutoConfiguration;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Role;
+import org.springframework.core.Ordered;
+import org.springframework.core.PriorityOrdered;
+import org.springframework.util.StringUtils;
+
+/**
+ * Applies configured provider-backed stores to Spring-managed retry matchers.
+ * Declare a {@link CredentialRetryStore} bean named {@code shiro.credential-retry.}
+ * to enable the store for matchers using that cache name.
+ */
+@AutoConfiguration
+public class CredentialRetryStoreAutoConfiguration {
+
+ /** Bean name prefix followed by the matcher's retry cache name. */
+ public static final String STORE_BEAN_PREFIX = "shiro.credential-retry.";
+
+ @Bean
+ @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
+ static CredentialRetryStoreBinder shiroCredentialRetryStoreBinder(BeanFactory beanFactory) {
+ return new CredentialRetryStoreBinder(beanFactory);
+ }
+
+ static final class CredentialRetryStoreBinder implements BeanPostProcessor, PriorityOrdered {
+
+ private final BeanFactory beanFactory;
+
+ CredentialRetryStoreBinder(BeanFactory beanFactory) {
+ this.beanFactory = beanFactory;
+ }
+
+ @Override
+ public Object postProcessAfterInitialization(Object bean, String beanName) {
+ Object target = bean instanceof AuthenticatingRealm realm ? realm.getCredentialsMatcher() : bean;
+ if (target instanceof DefaultCredentialsMatcher matcher && Objects.isNull(matcher.getCredentialRetryStore())) {
+ bind(matcher.getCredentialsRetryCacheName(), matcher::setCredentialRetryStore);
+ } else if (target instanceof CredentialsRetryLimitCredentialsMatcher matcher
+ && Objects.isNull(matcher.getCredentialRetryStore())) {
+ bind(matcher.getCredentialsRetryCacheName(), matcher::setCredentialRetryStore);
+ }
+ return bean;
+ }
+
+ @Override
+ public int getOrder() {
+ return Ordered.LOWEST_PRECEDENCE;
+ }
+
+ private void bind(String cacheName, Consumer setter) {
+ if (StringUtils.hasText(cacheName)) {
+ String beanName = STORE_BEAN_PREFIX + cacheName;
+ if (beanFactory.containsBean(beanName)) {
+ setter.accept(beanFactory.getBean(beanName, CredentialRetryStore.class));
+ }
+ }
+ }
+ }
+}
diff --git a/shiro-extension-spring/src/main/java/org/apache/shiro/biz/cache/spring/SpringCacheManager.java b/shiro-extension-spring/src/main/java/org/apache/shiro/biz/cache/spring/SpringCacheManager.java
index e8816257..f9fd3259 100644
--- a/shiro-extension-spring/src/main/java/org/apache/shiro/biz/cache/spring/SpringCacheManager.java
+++ b/shiro-extension-spring/src/main/java/org/apache/shiro/biz/cache/spring/SpringCacheManager.java
@@ -15,12 +15,15 @@
*/
package org.apache.shiro.biz.cache.spring;
+import org.apache.shiro.biz.authc.credential.CredentialRetryStore;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.apache.shiro.cache.CacheManager;
+import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
+import java.util.function.Function;
/**
* Spring CacheManager Wrapper
@@ -37,6 +40,23 @@ public SpringCacheManager(org.springframework.cache.CacheManager cacheManager){
this.delegator = cacheManager;
}
+ /**
+ * Binds a retry store to the named cache through its provider-specific factory.
+ *
+ * @param cacheName the Spring cache region whose retry policy is used
+ * @param providerFactory factory that opens an atomic retry store for the cache provider
+ * @return the provider-backed retry store
+ */
+ public CredentialRetryStore getCredentialRetryStore(
+ String cacheName, Function super org.springframework.cache.Cache, ? extends CredentialRetryStore> providerFactory) {
+ Objects.requireNonNull(providerFactory, "providerFactory");
+ org.springframework.cache.Cache springCache = delegator.getCache(cacheName);
+ if (Objects.isNull(springCache)) {
+ throw new CacheException("Spring retry cache is unavailable: " + cacheName);
+ }
+ return Objects.requireNonNull(providerFactory.apply(springCache), "providerStore");
+ }
+
@Override
public Cache getCache(String cacheName) throws CacheException {
SpringCache cache = this.CACHES.get(cacheName);
diff --git a/shiro-extension-spring/src/main/java/org/apache/shiro/biz/cache/spring/SpringDataRedisCredentialRetryStores.java b/shiro-extension-spring/src/main/java/org/apache/shiro/biz/cache/spring/SpringDataRedisCredentialRetryStores.java
new file mode 100644
index 00000000..adf9942e
--- /dev/null
+++ b/shiro-extension-spring/src/main/java/org/apache/shiro/biz/cache/spring/SpringDataRedisCredentialRetryStores.java
@@ -0,0 +1,122 @@
+package org.apache.shiro.biz.cache.spring;
+
+import java.nio.ByteBuffer;
+import java.util.List;
+import java.util.Objects;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.Function;
+import java.util.stream.Stream;
+import org.apache.shiro.biz.authc.credential.CredentialRetryStore;
+import org.apache.shiro.biz.cache.redis.RedisCredentialRetryStore;
+import org.springframework.cache.Cache;
+import org.springframework.cache.transaction.TransactionAwareCacheDecorator;
+import org.springframework.data.redis.cache.RedisCache;
+import org.springframework.data.redis.cache.RedisCacheConfiguration;
+import org.springframework.data.redis.connection.RedisConnection;
+import org.springframework.data.redis.connection.RedisConnectionFactory;
+import org.springframework.data.redis.connection.ReturnType;
+import org.springframework.data.redis.serializer.StringRedisSerializer;
+import org.springframework.data.redis.util.ByteUtils;
+
+/** Creates retry stores for Spring Data Redis 2.7 cache regions. */
+public final class SpringDataRedisCredentialRetryStores {
+
+ private static final StringRedisSerializer STRINGS = StringRedisSerializer.UTF_8;
+ private static final String SNAPSHOT_LEGACY = """
+ local value = redis.call('GET', KEYS[1])
+ if not value then
+ return {}
+ end
+ local ttl = redis.call('PTTL', KEYS[1])
+ if ttl == -2 then
+ return {}
+ end
+ if ttl == -1 then
+ return {value, 0}
+ end
+ local time = redis.call('TIME')
+ local now = tonumber(time[1]) * 1000 + math.floor(tonumber(time[2]) / 1000)
+ return {value, now + ttl}
+ """;
+
+ private SpringDataRedisCredentialRetryStores() {
+ }
+
+ /**
+ * Uses the cache's configured TTL and dedicated retry keys in the same Redis database.
+ *
+ * @param cache Spring Data Redis cache whose expiry policy is used
+ * @param connectionFactory connection factory used by that Redis cache
+ * @param namespace dedicated retry namespace shared by application instances
+ * @param principalKey stable principal encoding shared by application instances
+ * @return an atomic Redis retry store
+ */
+ public static CredentialRetryStore fromCache(Cache cache, RedisConnectionFactory connectionFactory,
+ String namespace, Function principalKey) {
+ return createStore(unwrap(cache), connectionFactory, namespace, principalKey);
+ }
+
+ /**
+ * Copies one legacy Spring Redis counter during an exclusive cache cutover.
+ * Complete the import before either old or new matchers resume using the region.
+ *
+ * @param cache existing Spring Redis retry cache
+ * @param connectionFactory connection factory used by the source and destination
+ * @param namespace distinct destination namespace used by the new retry store
+ * @param principalKey destination principal encoding used by the new retry store
+ * @param principal original string principal in the source region
+ * @return true when the provider copied a live counter into an empty destination key
+ */
+ public static boolean migrateLegacyWindow(Cache cache, RedisConnectionFactory connectionFactory,
+ String namespace, Function principalKey,
+ String principal) {
+ RedisCache source = unwrap(cache);
+ RedisCredentialRetryStore destination = createStore(source, connectionFactory, namespace, principalKey);
+ RedisCacheConfiguration configuration = source.getCacheConfiguration();
+ Objects.requireNonNull(principal, "principal");
+ String sourceKey = configuration.usePrefix()
+ ? configuration.getKeyPrefixFor(source.getName()) + principal : principal;
+ byte[] serializedKey = ByteUtils.getBytes(configuration.getKeySerializationPair().write(sourceKey));
+ List> snapshot;
+ try (RedisConnection connection = connectionFactory.getConnection()) {
+ snapshot = connection.scriptingCommands().eval(
+ STRINGS.serialize(SNAPSHOT_LEGACY), ReturnType.MULTI, 1, serializedKey);
+ }
+ if (snapshot.isEmpty()) {
+ return false;
+ }
+ Object value = configuration.getValueSerializationPair().read(ByteBuffer.wrap((byte[]) snapshot.get(0)));
+ if (!(value instanceof AtomicInteger)) {
+ throw new IllegalStateException("Spring Redis legacy retry entry must contain an AtomicInteger");
+ }
+ return destination.importFixedWindow(principal, ((AtomicInteger) value).get(), (Long) snapshot.get(1));
+ }
+
+ private static RedisCache unwrap(Cache cache) {
+ Cache target = cache;
+ while (target instanceof TransactionAwareCacheDecorator decorator) {
+ target = decorator.getTargetCache();
+ }
+ if (!(target instanceof RedisCache redisCache)) {
+ throw new IllegalArgumentException("Spring retry cache must be backed by Spring Data Redis");
+ }
+ return redisCache;
+ }
+
+ private static RedisCredentialRetryStore createStore(RedisCache redisCache, RedisConnectionFactory connectionFactory,
+ String namespace, Function principalKey) {
+ Objects.requireNonNull(connectionFactory, "connectionFactory");
+ return new RedisCredentialRetryStore(
+ (script, keys, args) -> eval(connectionFactory, script, keys, args),
+ namespace, principalKey, redisCache.getCacheConfiguration().getTtl());
+ }
+
+ private static String eval(RedisConnectionFactory factory, String script, List keys, List args) {
+ byte[][] arguments = Stream.concat(keys.stream(), args.stream()).map(STRINGS::serialize).toArray(byte[][]::new);
+ try (RedisConnection connection = factory.getConnection()) {
+ byte[] result = connection.scriptingCommands().eval(
+ STRINGS.serialize(script), ReturnType.VALUE, keys.size(), arguments);
+ return STRINGS.deserialize(result);
+ }
+ }
+}
diff --git a/shiro-extension-spring/src/main/java/org/apache/shiro/biz/cache/spring/SpringJCacheCredentialRetryStores.java b/shiro-extension-spring/src/main/java/org/apache/shiro/biz/cache/spring/SpringJCacheCredentialRetryStores.java
new file mode 100644
index 00000000..90a09855
--- /dev/null
+++ b/shiro-extension-spring/src/main/java/org/apache/shiro/biz/cache/spring/SpringJCacheCredentialRetryStores.java
@@ -0,0 +1,25 @@
+package org.apache.shiro.biz.cache.spring;
+
+import org.apache.shiro.biz.authc.credential.CredentialRetryStore;
+import org.apache.shiro.biz.cache.jcache.JCacheCredentialRetryStore;
+import org.springframework.cache.Cache;
+
+/** Creates retry stores for Spring cache regions backed by JCache. */
+public final class SpringJCacheCredentialRetryStores {
+
+ private SpringJCacheCredentialRetryStores() {
+ }
+
+ /**
+ * @param cache Spring cache exposing a dedicated JCache region for retry attempts
+ * @return a retry store using the provider's atomic entry processing and expiry
+ */
+ @SuppressWarnings("unchecked")
+ public static CredentialRetryStore fromCache(Cache cache) {
+ if (!(cache.getNativeCache() instanceof javax.cache.Cache, ?> nativeCache)) {
+ throw new IllegalArgumentException("Spring retry cache must expose a JCache region");
+ }
+
+ return new JCacheCredentialRetryStore((javax.cache.Cache) nativeCache);
+ }
+}
diff --git a/shiro-extension-spring/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/shiro-extension-spring/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
new file mode 100644
index 00000000..2de1ddfd
--- /dev/null
+++ b/shiro-extension-spring/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
@@ -0,0 +1 @@
+org.apache.shiro.biz.authc.credential.spring.CredentialRetryStoreAutoConfiguration
diff --git a/shiro-extension-spring/src/test/java/org/apache/shiro/biz/authc/credential/spring/CredentialRetryStoreAutoConfigurationTest.java b/shiro-extension-spring/src/test/java/org/apache/shiro/biz/authc/credential/spring/CredentialRetryStoreAutoConfigurationTest.java
new file mode 100644
index 00000000..a471a0db
--- /dev/null
+++ b/shiro-extension-spring/src/test/java/org/apache/shiro/biz/authc/credential/spring/CredentialRetryStoreAutoConfigurationTest.java
@@ -0,0 +1,160 @@
+package org.apache.shiro.biz.authc.credential.spring;
+
+import java.util.concurrent.atomic.AtomicInteger;
+import org.apache.shiro.authc.ExcessiveAttemptsException;
+import org.apache.shiro.authc.IncorrectCredentialsException;
+import org.apache.shiro.authc.SimpleAuthenticationInfo;
+import org.apache.shiro.authc.UsernamePasswordToken;
+import org.apache.shiro.authc.credential.AllowAllCredentialsMatcher;
+import org.apache.shiro.biz.authc.credential.CredentialRetryStore;
+import org.apache.shiro.biz.authc.credential.CredentialsRetryLimitCredentialsMatcher;
+import org.apache.shiro.biz.authc.credential.DefaultCredentialsMatcher;
+import org.apache.shiro.cache.MemoryConstrainedCacheManager;
+import org.apache.shiro.realm.SimpleAccountRealm;
+import org.junit.Test;
+import org.springframework.beans.factory.BeanCreationException;
+import org.springframework.beans.factory.BeanNotOfRequiredTypeException;
+import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
+import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
+import org.springframework.context.annotation.AnnotationConfigApplicationContext;
+import org.springframework.context.annotation.Configuration;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertThrows;
+
+public class CredentialRetryStoreAutoConfigurationTest {
+
+ @Test
+ public void bootDiscoversBindingsForBothMatcherTypesByTheirCacheNames() {
+ var first = new RecordingStore();
+ var second = new RecordingStore();
+ try (var context = context()) {
+ context.registerBean(storeName("password"), CredentialRetryStore.class, () -> first);
+ context.registerBean(storeName("hashed"), CredentialRetryStore.class, () -> second);
+ context.registerBean("passwordMatcher", DefaultCredentialsMatcher.class, () -> passwordMatcher("password"));
+ context.registerBean(CredentialsRetryLimitCredentialsMatcher.class, this::hashedMatcher);
+ context.refresh();
+
+ var password = context.getBean(DefaultCredentialsMatcher.class);
+ var hashed = context.getBean(CredentialsRetryLimitCredentialsMatcher.class);
+ assertSame(first, password.getCredentialRetryStore());
+ assertSame(second, hashed.getCredentialRetryStore());
+ assertFalse(password.doCredentialsMatch(
+ new UsernamePasswordToken("principal", "wrong"),
+ new SimpleAuthenticationInfo("principal", "correct", "realm")));
+ assertEquals(1, first.attempts.get());
+ assertEquals(0, second.attempts.get());
+ }
+ }
+
+ @Test
+ public void keepsExplicitStoreAndUnconfiguredMatchers() {
+ var assigned = new RecordingStore();
+ try (var context = context()) {
+ context.registerBean(storeName("manual"), CredentialRetryStore.class, RecordingStore::new);
+ context.registerBean("manual", DefaultCredentialsMatcher.class, () -> {
+ var matcher = passwordMatcher("manual");
+ matcher.setCredentialRetryStore(assigned);
+ return matcher;
+ });
+ context.registerBean("legacy", DefaultCredentialsMatcher.class, () -> {
+ var matcher = passwordMatcher("legacy");
+ matcher.setCacheManager(new MemoryConstrainedCacheManager());
+ matcher.setRetryLimit(2);
+ return matcher;
+ });
+ context.registerBean(AllowAllCredentialsMatcher.class, AllowAllCredentialsMatcher::new);
+ context.refresh();
+
+ var manual = context.getBean("manual", DefaultCredentialsMatcher.class);
+ assertSame(assigned, manual.getCredentialRetryStore());
+
+ var legacy = context.getBean("legacy", DefaultCredentialsMatcher.class);
+ assertNull(legacy.getCredentialRetryStore());
+ var rejected = new UsernamePasswordToken("principal", "wrong");
+ var account = new SimpleAuthenticationInfo("principal", "correct", "realm");
+ assertFalse(legacy.doCredentialsMatch(rejected, account));
+ assertThrows(ExcessiveAttemptsException.class, () -> legacy.doCredentialsMatch(rejected, account));
+
+ context.getBean(AllowAllCredentialsMatcher.class);
+ }
+ }
+
+ @Test
+ public void bindsAnInlineMatcherThroughItsSpringManagedRealm() {
+ var store = new RecordingStore();
+ try (var context = context()) {
+ context.registerBean(storeName("inline"), CredentialRetryStore.class, () -> store);
+ context.registerBean(SimpleAccountRealm.class, () -> {
+ var realm = new SimpleAccountRealm();
+ var matcher = passwordMatcher("inline");
+ matcher.setRetryLimit(2);
+ realm.setCredentialsMatcher(matcher);
+ realm.addAccount("principal", "correct");
+ return realm;
+ });
+ context.refresh();
+
+ var realm = context.getBean(SimpleAccountRealm.class);
+ var rejected = new UsernamePasswordToken("principal", "wrong");
+ assertThrows(IncorrectCredentialsException.class, () -> realm.getAuthenticationInfo(rejected));
+ assertThrows(ExcessiveAttemptsException.class, () -> realm.getAuthenticationInfo(rejected));
+ assertEquals(2, store.attempts.get());
+ }
+ }
+
+ @Test
+ public void reportsARegionBeanWithTheWrongTypeAtStartup() {
+ try (var context = context()) {
+ context.registerBean(storeName("password"), String.class, () -> "incorrect type");
+ context.registerBean(DefaultCredentialsMatcher.class, () -> passwordMatcher("password"));
+ BeanCreationException failure = assertThrows(BeanCreationException.class, context::refresh);
+ assertEquals(BeanNotOfRequiredTypeException.class, failure.getMostSpecificCause().getClass());
+ }
+ }
+
+ private static AnnotationConfigApplicationContext context() {
+ var context = new AnnotationConfigApplicationContext();
+ context.register(BootConfiguration.class);
+ return context;
+ }
+
+ private static String storeName(String region) {
+ return CredentialRetryStoreAutoConfiguration.STORE_BEAN_PREFIX + region;
+ }
+
+ private static DefaultCredentialsMatcher passwordMatcher(String region) {
+ var matcher = new DefaultCredentialsMatcher();
+ matcher.setCredentialsRetryCacheName(region);
+ return matcher;
+ }
+
+ private CredentialsRetryLimitCredentialsMatcher hashedMatcher() {
+ var matcher = new CredentialsRetryLimitCredentialsMatcher();
+ matcher.setCredentialsRetryCacheName("hashed");
+ return matcher;
+ }
+
+ @Configuration(proxyBeanMethods = false)
+ @EnableAutoConfiguration(exclude = RedisAutoConfiguration.class)
+ static class BootConfiguration {
+ }
+
+ private static final class RecordingStore implements CredentialRetryStore {
+
+ private final AtomicInteger attempts = new AtomicInteger();
+
+ @Override
+ public Attempt reserve(Object principal) {
+ return new Attempt("window", attempts.incrementAndGet());
+ }
+
+ @Override
+ public void clearIfCurrent(Object principal, String windowId) {
+ attempts.set(0);
+ }
+ }
+}
diff --git a/shiro-extension-spring/src/test/java/org/apache/shiro/biz/cache/spring/SpringCredentialRetryStoreIntegrationTest.java b/shiro-extension-spring/src/test/java/org/apache/shiro/biz/cache/spring/SpringCredentialRetryStoreIntegrationTest.java
new file mode 100644
index 00000000..20c8fbc0
--- /dev/null
+++ b/shiro-extension-spring/src/test/java/org/apache/shiro/biz/cache/spring/SpringCredentialRetryStoreIntegrationTest.java
@@ -0,0 +1,279 @@
+package org.apache.shiro.biz.cache.spring;
+
+import com.hazelcast.cache.impl.HazelcastServerCachingProvider;
+import com.hazelcast.config.Config;
+import com.hazelcast.core.Hazelcast;
+import com.hazelcast.core.HazelcastInstance;
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Arrays;
+import java.util.Objects;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.Callable;
+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.AtomicInteger;
+import java.util.function.Function;
+import javax.cache.Cache;
+import javax.cache.configuration.MutableConfiguration;
+import javax.cache.expiry.EternalExpiryPolicy;
+import org.apache.shiro.authc.ExcessiveAttemptsException;
+import org.apache.shiro.authc.SimpleAuthenticationInfo;
+import org.apache.shiro.authc.UsernamePasswordToken;
+import org.apache.shiro.biz.authc.credential.CredentialRetryStore;
+import org.apache.shiro.biz.authc.credential.CredentialRetryStore.Attempt;
+import org.apache.shiro.biz.authc.credential.DefaultCredentialsMatcher;
+import org.apache.shiro.biz.authc.credential.spring.CredentialRetryStoreAutoConfiguration;
+import org.apache.shiro.cache.CacheException;
+import org.junit.Test;
+import org.springframework.cache.concurrent.ConcurrentMapCache;
+import org.springframework.cache.jcache.JCacheCacheManager;
+import org.springframework.cache.support.SimpleCacheManager;
+import org.springframework.context.annotation.AnnotationConfigApplicationContext;
+import org.springframework.data.redis.cache.RedisCacheConfiguration;
+import org.springframework.data.redis.cache.RedisCacheManager;
+import org.springframework.data.redis.connection.RedisClusterConfiguration;
+import org.springframework.data.redis.connection.RedisClusterConnection;
+import org.springframework.data.redis.connection.RedisConnection;
+import org.springframework.data.redis.connection.ReturnType;
+import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
+import org.springframework.data.redis.serializer.StringRedisSerializer;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertThrows;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assume.assumeTrue;
+
+public class SpringCredentialRetryStoreIntegrationTest {
+
+ private static final String CLUSTER_NODES = "shiro.redis.test.cluster.nodes";
+ private static final String REGION = "credential-retry";
+ private static final StringRedisSerializer UTF_8 = StringRedisSerializer.UTF_8;
+
+ @Test
+ public void springRedisManagersShareAnAtomicRetryWindowWithTheirConfiguredTtl() throws Exception {
+ String port = System.getProperty("shiro.redis.test.port");
+ assumeTrue("Supply an isolated Redis port", Objects.nonNull(port));
+ String namespace = "test:spring-retry:" + UUID.randomUUID();
+ LettuceConnectionFactory first = connectionFactory(port);
+ LettuceConnectionFactory second = connectionFactory(port);
+ try {
+ CredentialRetryStore a = redisStore(first, namespace, false);
+ CredentialRetryStore b = redisStore(second, namespace, true);
+ Attempt initial = a.reserve("principal");
+ long deadline = expiry(first, namespace);
+ assertTrue(deadline > System.currentTimeMillis());
+ assertTrue(deadline <= System.currentTimeMillis() + 15_000);
+
+ ExecutorService workers = Executors.newFixedThreadPool(6);
+ try {
+ List> requests = new ArrayList<>();
+ for (int i = 0; i < 24; i++) {
+ CredentialRetryStore selected = i % 2 == 0 ? a : b;
+ requests.add(() -> selected.reserve("principal"));
+ }
+ Set counts = new HashSet<>();
+ for (Future result : workers.invokeAll(requests, 10, TimeUnit.SECONDS)) {
+ Attempt attempt = result.get();
+ assertEquals(initial.getWindowId(), attempt.getWindowId());
+ assertTrue(counts.add(attempt.getCount()));
+ }
+ assertEquals(24, counts.size());
+ assertTrue(counts.contains(2));
+ assertTrue(counts.contains(25));
+ } finally {
+ workers.shutdownNow();
+ }
+ assertEquals(deadline, expiry(second, namespace));
+ b.clearIfCurrent("principal", initial.getWindowId());
+ Attempt renewed = a.reserve("principal");
+ assertEquals(1, renewed.getCount());
+ assertNotEquals(initial.getWindowId(), renewed.getWindowId());
+ b.clearIfCurrent("principal", initial.getWindowId());
+ assertEquals(2, a.reserve("principal").getCount());
+ } finally {
+ second.destroy();
+ first.destroy();
+ }
+ }
+
+ @Test
+ public void importsSpringRedisLegacyCountersWithTheOriginalDeadline() throws Exception {
+ String port = System.getProperty("shiro.redis.test.port");
+ String nodes = System.getProperty(CLUSTER_NODES);
+ assumeTrue("Supply an isolated Redis port or cluster nodes", Objects.nonNull(port) || Objects.nonNull(nodes));
+ String namespace = "{retry-current}:test:spring-migrate:" + UUID.randomUUID();
+ LettuceConnectionFactory factory = migrationConnectionFactory(port, nodes);
+ try {
+ String legacyPrefix = "{retry-legacy}:test:spring-migrate:" + UUID.randomUUID() + ":";
+ verifyDifferentOwners(factory, legacyPrefix + "principal", namespace + ":principal");
+ RedisCacheManager manager = RedisCacheManager.builder(factory)
+ .cacheDefaults(RedisCacheConfiguration.defaultCacheConfig()
+ .computePrefixWith(name -> legacyPrefix).entryTtl(Duration.ofSeconds(5)))
+ .transactionAware().build();
+ manager.afterPropertiesSet();
+ org.springframework.cache.Cache source = manager.getCache(REGION);
+ source.put("principal", new AtomicInteger(3));
+ long deadline = expiryKey(factory, legacyPrefix + "principal");
+ assertTrue(deadline > System.currentTimeMillis());
+
+ Function encoding = Object::toString;
+ assertTrue(SpringDataRedisCredentialRetryStores.migrateLegacyWindow(source, factory, namespace, encoding, "principal"));
+ assertFalse(SpringDataRedisCredentialRetryStores.migrateLegacyWindow(source, factory, namespace, encoding, "principal"));
+ assertFalse(SpringDataRedisCredentialRetryStores.migrateLegacyWindow(source, factory, namespace, encoding, "missing"));
+ assertEquals(3, source.get("principal", AtomicInteger.class).get());
+ assertEquals(deadline, expiry(factory, namespace));
+
+ Attempt next = redisStore(factory, namespace, false).reserve("principal");
+ assertEquals(4, next.getCount());
+ assertEquals(deadline, expiry(factory, namespace));
+ } finally {
+ factory.destroy();
+ }
+ }
+
+ @Test
+ public void springRedisEnforcesTheRetryLimitAcrossMatcherInstances() {
+ String port = System.getProperty("shiro.redis.test.port");
+ assumeTrue("Supply an isolated Redis port", Objects.nonNull(port));
+ String namespace = "test:spring-matcher:" + UUID.randomUUID();
+ LettuceConnectionFactory first = connectionFactory(port);
+ LettuceConnectionFactory second = connectionFactory(port);
+ try (var firstContext = matcherContext(first, namespace, false);
+ var secondContext = matcherContext(second, namespace, true)) {
+ var a = firstContext.getBean(DefaultCredentialsMatcher.class);
+ var b = secondContext.getBean(DefaultCredentialsMatcher.class);
+
+ var rejected = new UsernamePasswordToken("principal", "wrong");
+ var account = new SimpleAuthenticationInfo("principal", "correct", "realm");
+ assertFalse(a.doCredentialsMatch(rejected, account));
+ assertFalse(b.doCredentialsMatch(rejected, account));
+ assertThrows(ExcessiveAttemptsException.class, () -> a.doCredentialsMatch(rejected, account));
+ } finally {
+ second.destroy();
+ first.destroy();
+ }
+ }
+
+ @Test
+ public void unwrapsSpringJCacheThroughTheShiroCacheManager() {
+ Config config = new Config().setClusterName("shiro-spring-jcache-" + UUID.randomUUID());
+ config.setProperty("hazelcast.logging.type", "none");
+ config.setProperty("hazelcast.socket.bind.any", "false");
+ config.setProperty("hazelcast.operation.thread.count", "2");
+ config.setProperty("hazelcast.operation.generic.thread.count", "2");
+ config.setProperty("hazelcast.io.thread.count", "2");
+ config.setProperty("hazelcast.event.thread.count", "2");
+ config.getNetworkConfig().getInterfaces().setEnabled(true).addInterface("127.0.0.1");
+ config.getNetworkConfig().getJoin().getAutoDetectionConfig().setEnabled(false);
+ config.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(false);
+ HazelcastInstance member = Hazelcast.newHazelcastInstance(config);
+ try (HazelcastServerCachingProvider provider = new HazelcastServerCachingProvider(member);
+ javax.cache.CacheManager nativeManager = provider.getCacheManager()) {
+ Cache region = nativeManager.createCache(REGION, new MutableConfiguration()
+ .setTypes(Object.class, Object.class)
+ .setExpiryPolicyFactory(EternalExpiryPolicy.factoryOf()));
+ region.put("principal", new AtomicInteger(3));
+ JCacheCacheManager spring = new JCacheCacheManager(nativeManager);
+ spring.afterPropertiesSet();
+ SpringCacheManager shiro = new SpringCacheManager(spring);
+ CredentialRetryStore a = shiro.getCredentialRetryStore(REGION, SpringJCacheCredentialRetryStores::fromCache);
+ CredentialRetryStore b = shiro.getCredentialRetryStore(REGION, SpringJCacheCredentialRetryStores::fromCache);
+ Attempt initial = a.reserve("principal");
+ assertEquals(4, initial.getCount());
+ assertEquals(initial.getWindowId(), b.reserve("principal").getWindowId());
+ assertEquals(5, ((Attempt) region.get("principal")).getCount());
+ b.clearIfCurrent("principal", initial.getWindowId());
+ assertEquals(1, a.reserve("principal").getCount());
+ } finally {
+ member.getLifecycleService().terminate();
+ }
+ }
+
+ @Test
+ public void reportsMissingRegionsAndRejectsCachesWithoutTheExpectedProvider() {
+ SimpleCacheManager spring = new SimpleCacheManager();
+ spring.setCaches(List.of(new ConcurrentMapCache(REGION)));
+ spring.afterPropertiesSet();
+ SpringCacheManager shiro = new SpringCacheManager(spring);
+ assertThrows(CacheException.class,
+ () -> shiro.getCredentialRetryStore("missing", SpringJCacheCredentialRetryStores::fromCache));
+ assertThrows(IllegalArgumentException.class,
+ () -> shiro.getCredentialRetryStore(REGION, SpringJCacheCredentialRetryStores::fromCache));
+ }
+
+ private static AnnotationConfigApplicationContext matcherContext(
+ LettuceConnectionFactory factory, String namespace, boolean transactionAware) {
+ var context = new AnnotationConfigApplicationContext();
+ context.register(CredentialRetryStoreAutoConfiguration.class);
+ context.registerBean(CredentialRetryStoreAutoConfiguration.STORE_BEAN_PREFIX + REGION,
+ CredentialRetryStore.class, () -> redisStore(factory, namespace, transactionAware));
+ context.registerBean(DefaultCredentialsMatcher.class, () -> {
+ var matcher = new DefaultCredentialsMatcher();
+ matcher.setRetryLimit(3);
+ matcher.setCredentialsRetryCacheName(REGION);
+ return matcher;
+ });
+ context.refresh();
+ return context;
+ }
+
+ private static LettuceConnectionFactory migrationConnectionFactory(String port, String nodes) {
+ if (Objects.isNull(nodes)) {
+ return connectionFactory(port);
+ }
+ LettuceConnectionFactory factory = new LettuceConnectionFactory(
+ new RedisClusterConfiguration(Arrays.asList(nodes.split(","))));
+ factory.afterPropertiesSet();
+ return factory;
+ }
+
+ private static void verifyDifferentOwners(LettuceConnectionFactory factory, String source, String destination) {
+ if (Objects.nonNull(System.getProperty(CLUSTER_NODES))) {
+ try (RedisClusterConnection cluster = factory.getClusterConnection()) {
+ String sourceOwner = cluster.clusterGetNodeForKey(UTF_8.serialize(source)).getId();
+ String destinationOwner = cluster.clusterGetNodeForKey(UTF_8.serialize(destination)).getId();
+ assertNotEquals("Migration must cross Redis primary nodes", sourceOwner, destinationOwner);
+ }
+ }
+ }
+
+ private static LettuceConnectionFactory connectionFactory(String port) {
+ LettuceConnectionFactory factory = new LettuceConnectionFactory("127.0.0.1", Integer.parseInt(port));
+ factory.afterPropertiesSet();
+ return factory;
+ }
+
+ private static CredentialRetryStore redisStore(LettuceConnectionFactory factory, String namespace,
+ boolean transactionAware) {
+ var builder = RedisCacheManager.builder(factory)
+ .withCacheConfiguration(REGION, RedisCacheConfiguration.defaultCacheConfig()
+ .entryTtl(Duration.ofSeconds(15)));
+ if (transactionAware) {
+ builder.transactionAware();
+ }
+ RedisCacheManager spring = builder.build();
+ spring.afterPropertiesSet();
+ return new SpringCacheManager(spring).getCredentialRetryStore(REGION,
+ cache -> SpringDataRedisCredentialRetryStores.fromCache(cache, factory, namespace, Object::toString));
+ }
+
+ private static long expiry(LettuceConnectionFactory factory, String namespace) {
+ return expiryKey(factory, namespace + ":principal");
+ }
+
+ private static long expiryKey(LettuceConnectionFactory factory, String key) {
+ try (RedisConnection connection = factory.getConnection()) {
+ return connection.scriptingCommands().eval(
+ UTF_8.serialize("return redis.call('PEXPIRETIME', KEYS[1])"),
+ ReturnType.INTEGER, 1, UTF_8.serialize(key));
+ }
+ }
+}