Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/pull_request_5x.yml
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,4 @@ jobs:
key: ${{ runner.os }}-${{ hashFiles('**/pom.xml') }}
- name: Build changed modules with Maven
# The Maven cache may contain a snapshot published before an upstream API change.
run: ./mvnw -U test -q -pl "$(./changes.sh)" -am
run: ./mvnw -U test -q -Dtest.redis.port=6379 -pl "$(./changes.sh)" -am
25 changes: 25 additions & 0 deletions hsweb-authorization/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,28 @@
1. [hsweb-authorization-api](hsweb-authorization-api):权限控制API
3. [hsweb-authorization-basic](hsweb-authorization-basic):权限控制基础实现

## Redis 用户令牌索引

`RedisUserTokenManager` 使用带独立 TTL 的 `user-token:{token}` Hash 保存令牌,
`user-token-user:{userId}` Set 是最终一致的用户索引,不能作为令牌有效性的唯一依据。
永久令牌和仍存在的锁定、下线记录继续保留索引;整个 Set 不使用单个令牌的 TTL。

按用户查询采用游标扫描,只返回当前归属的令牌,不在读取链路删除或补回索引,避免读取短路取消截断索引维护。
宿主应周期调用 `checkExpiredToken()` 回收自然过期、
缺少必要字段或归属错误的索引;该方法不依赖本地缓存、不直接删除令牌 Hash,也不发布主动退出事件。
扫描允许重复,清理可重试;并发签发与索引维护不构成跨 key 事务。

批量续期在同一 Hash 上原子校验身份、签发时间和闲置超时快照,再更新访问时间、TTL;
延迟续期既不重建已删除的记录,也不覆盖同 Token 重签后的新会话。签发事件调整有效期时,
返回对象、本地缓存和 Redis 使用一致的闲置超时;重签为永久 Token 时移除旧 TTL。
该管理器拥有的后台订阅由 `close()` 取消,Redis 连接由宿主管理;手动创建的实例也应在停止时关闭。

## OAuth2 令牌管理器装配

`RedisAccessTokenManager` 通过 `(ReactiveRedisOperations<String, RedisAccessToken>, UserTokenManager)`
显式注入依赖,用户会话操作复用应用配置的 `UserTokenManager`,其创建、配置和销毁由宿主负责。
默认 Spring 自动装配已复用该 Bean;OAuth2 不创建或关闭用户令牌管理器。

原 `RedisAccessTokenManager(ReactiveRedisConnectionFactory)` 构造器已移除,依赖它的调用方须迁移到双参数构造器。
手动装配时,显式创建 Redis operations 和 `UserTokenManager`,并在宿主停止时关闭自己创建的
`RedisUserTokenManager`;容器装配时由容器销毁共享 Bean。
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.hswebframework.web.authorization.Authentication;
import org.hswebframework.web.authorization.exception.AccessDenyException;
import org.hswebframework.web.authorization.token.*;
Expand All @@ -13,21 +14,48 @@
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.data.redis.connection.ReactiveRedisConnectionFactory;
import org.springframework.data.redis.core.*;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import reactor.core.publisher.Flux;
import reactor.core.publisher.FluxSink;
import reactor.core.publisher.Mono;
import reactor.core.Disposable;
import reactor.core.Disposables;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Consumer;
import java.util.stream.Collectors;

public class RedisUserTokenManager implements UserTokenManager {
/** Redis Token storage with an eventually consistent user index; close owned subscriptions on shutdown. */
@Slf4j
public class RedisUserTokenManager implements UserTokenManager, AutoCloseable {

private static final String USER_KEY_PREFIX = "user-token-user:";

private static final int TOKEN_CONCURRENCY = 16;

private static final ScanOptions TOKEN_SCAN_OPTIONS = ScanOptions.scanOptions().count(256).build();

// Guard the issuance snapshot; a delayed touch must not overwrite a reissued token.
private static final RedisScript<Long> TOUCH_SCRIPT = RedisScript.of(
"if redis.call('HGET', KEYS[1], ARGV[1]) ~= ARGV[2] " +
"or redis.call('HGET', KEYS[1], ARGV[3]) ~= ARGV[4] " +
"or redis.call('HGET', KEYS[1], ARGV[5]) ~= ARGV[6] " +
"or redis.call('HGET', KEYS[1], ARGV[7]) ~= ARGV[8] then return 0 end " +
"redis.call('HSET', KEYS[1], ARGV[9], ARGV[10]) " +
"return redis.call('PEXPIRE', KEYS[1], ARGV[11])", Long.class);

private final Disposable.Composite subscriptions = Disposables.composite();

private final ReactiveRedisOperations<Object, Object> operations;

Expand All @@ -44,23 +72,20 @@ public RedisUserTokenManager(ReactiveRedisOperations<Object, Object> operations)
this.operations = operations;
this.userTokenStore = operations.opsForHash();
this.userTokenMapping = operations.opsForSet();
this.operations
subscriptions.add(this.operations
.listenToChannel("_user_token_removed")
.subscribe(msg -> localCache.remove(String.valueOf(msg.getMessage())));
.subscribe(msg -> localCache.remove(String.valueOf(msg.getMessage())),
error -> log.warn("User token invalidation subscription failed: {}", error.getClass().getSimpleName())));

Flux.<UserToken>create(sink -> this.touchSink = sink)
subscriptions.add(Flux.<UserToken>create(sink -> this.touchSink = sink)
.buffer(Flux.interval(Duration.ofSeconds(10)), HashSet::new)
.flatMap(list -> Flux
.fromIterable(list)
.flatMap(token -> {
String key = getTokenRedisKey(token.getToken());
return Mono
.zip(this.userTokenStore.put(key, "lastRequestTime", token.getLastRequestTime()),
this.operations.expire(key, Duration.ofMillis(token.getMaxInactiveInterval())))
.then();
})
.onErrorResume(err -> Mono.empty()))
.subscribe();
.flatMap(token -> touchToken(token).onErrorResume(error -> {
log.warn("User token touch failed: {}", error.getClass().getSimpleName());
return Mono.empty();
}), TOKEN_CONCURRENCY))
.subscribe());

}

Expand Down Expand Up @@ -98,7 +123,7 @@ private String getTokenRedisKey(String key) {
}

private String getUserRedisKey(String key) {
return "user-token-user:".concat(key);
return USER_KEY_PREFIX.concat(key);
}

@Override
Expand All @@ -120,12 +145,10 @@ public Mono<UserToken> getByToken(String token) {
public Flux<UserToken> getByUserId(String userId) {
String redisKey = getUserRedisKey(userId);
return userTokenMapping
.members(redisKey)
.scan(redisKey, TOKEN_SCAN_OPTIONS)
.map(String::valueOf)
.flatMap(token -> getByToken(token)
.switchIfEmpty(Mono.defer(() -> userTokenMapping
.remove(redisKey, token)
.then(Mono.empty()))));
.filter(userToken -> userId.equals(userToken.getUserId())), TOKEN_CONCURRENCY);
}

@Override
Expand Down Expand Up @@ -245,13 +268,13 @@ protected Mono<SimpleUserToken> sign0(String token,
return this
.publishEvent(event)
.then(Mono.defer(() -> {
map.put("maxInactiveInterval", event.getExpires());
if (event.getExpires() > 0) {
return userTokenStore
.putAll(key, map)
.then(operations.expire(key, Duration.ofMillis(event.getExpires())));
}
return userTokenStore.putAll(key, map);
long effectiveExpires = event.getExpires();
userToken.setMaxInactiveInterval(effectiveExpires);
map.put("maxInactiveInterval", effectiveExpires);
return userTokenStore.putAll(key, map)
.then(effectiveExpires > 0
? operations.expire(key, Duration.ofMillis(effectiveExpires))
: operations.persist(key));
}))
.then(userTokenMapping.add(getUserRedisKey(userId), token))
.thenReturn(userToken);
Expand Down Expand Up @@ -347,22 +370,74 @@ public Mono<Void> touch(String token) {

@Override
public Mono<Void> checkExpiredToken() {

return operations
.scan(ScanOptions.scanOptions().match("*user-token-user:*").build())
.map(String::valueOf)
.flatMap(key -> userTokenMapping
.members(key)
return Mono.defer(() -> {
long started = System.nanoTime();
AtomicLong checked = new AtomicLong();
AtomicLong removed = new AtomicLong();
return operations
.scan(ScanOptions.scanOptions().match("*" + USER_KEY_PREFIX + "*").count(256).build())
.map(String::valueOf)
.flatMap(token -> operations
.hasKey(getTokenRedisKey(token))
.flatMap(exists -> {
if (!exists) {
return userTokenMapping.remove(key, token);
}
return Mono.empty();
})))
.then();
// Serial user scans keep the total number of in-flight member checks bounded.
.concatMap(key -> {
String userId = key.substring(key.indexOf(USER_KEY_PREFIX) + USER_KEY_PREFIX.length());
return userTokenMapping
.scan(key, TOKEN_SCAN_OPTIONS)
.map(String::valueOf)
.flatMap(token -> {
checked.incrementAndGet();
return tokenBelongsTo(token, userId)
.flatMap(valid -> valid ? Mono.just(0L) : removeInvalidMapping(key, userId, token))
.doOnNext(removed::addAndGet);
}, TOKEN_CONCURRENCY);
}, 1)
.then()
.doOnSuccess(ignore -> log.debug("User token index checked: members={}, removed={}, durationMs={}",
checked.get(), removed.get(), (System.nanoTime() - started) / 1_000_000));
});
}

private Mono<Boolean> tokenBelongsTo(String token, String userId) {
return userTokenStore
.multiGet(getTokenRedisKey(token), Arrays.asList("token", "userId"))
.map(values -> token.equals(values.get(0)) && userId.equals(values.get(1)));
}

private Mono<Long> removeInvalidMapping(String key, String userId, String token) {
return userTokenMapping.remove(key, token)
// A concurrent sign-in can recreate this token between the first read and SREM.
.flatMap(removed -> tokenBelongsTo(token, userId)
.flatMap(valid -> valid
? userTokenMapping.add(key, token).thenReturn(0L)
: Mono.just(removed)));
}

Mono<Void> touchToken(UserToken token) {
if (token.getMaxInactiveInterval() <= 0) {
return Mono.empty();
}
RedisSerializationContext<Object, Object> serialization = operations.getSerializationContext();
// Hash arguments retain the template codecs; only PEXPIRE's TTL uses plain-text milliseconds.
return operations.execute(TOUCH_SCRIPT,
Collections.singletonList(getTokenRedisKey(token.getToken())),
Arrays.asList(serialization.getHashKeySerializationPair().write("token"),
serialization.getHashValueSerializationPair().write(token.getToken()),
serialization.getHashKeySerializationPair().write("userId"),
serialization.getHashValueSerializationPair().write(token.getUserId()),
serialization.getHashKeySerializationPair().write("signInTime"),
serialization.getHashValueSerializationPair().write(token.getSignInTime()),
serialization.getHashKeySerializationPair().write("maxInactiveInterval"),
serialization.getHashValueSerializationPair().write(token.getMaxInactiveInterval()),
serialization.getHashKeySerializationPair().write("lastRequestTime"),
serialization.getHashValueSerializationPair().write(token.getLastRequestTime()),
ByteBuffer.wrap(Long.toString(token.getMaxInactiveInterval()).getBytes(StandardCharsets.US_ASCII))),
value -> (ByteBuffer) value,
buffer -> Long.parseLong(StandardCharsets.US_ASCII.decode(buffer).toString()))
.then();
}

@Override
public void close() {
subscriptions.dispose();
}

private Mono<Void> notifyTokenRemoved(String token) {
Expand Down
Loading
Loading