在响应式链路中如何整合 TOTP?
解读
国内互联网大厂(阿里、字节、美团等)在零信任架构下普遍要求登录、支付、运维操作等关键链路具备双因子认证(2FA)。TOTP(Time-based One-Time Password)因其离线生成、算法公开、无额外硬件成本成为首选。Spring 5 全面拥抱响应式编程(WebFlux + Reactor),传统基于阻塞过滤器(Servlet Filter)的 TOTP 方案(如 spring-security-totp-starter)在 Netty 容器下会拖垮事件循环线程,因此面试重点考察:
- 能否把“同步加密运算”变成“非阻塞异步”;
- 能否利用响应式会话管理(Reactive Session)实现无状态漂移;
- 能否与国内合规要求(国密 SM3 可选、脱敏日志、等保三级留存 180 天)对齐。
回答必须体现“Reactive + TOTP”与“传统阻塞方案”的差异,并给出可落地的 Spring 代码级设计。
知识点
- TOTP 算法核心:HMAC-SHA1/256/512(密钥, 时间戳/30) → 动态截断 → 6~8 位数字;RFC 6238 标准。
- 响应式链路关键组件:
- WebFilter(org.springframework.web.server.WebFilter)——非阻塞入口;
- ReactiveAuthenticationManager——认证逻辑必须返回 Mono<Authentication>;
- ServerSecurityContextRepository——替代 HttpSession,基于 Redis 响应式会话;
- Scheduler.boundedElastic()——把 CPU 密集或加密运算 offload 到弹性线程池,防止 EventLoop 饥饿;
- 密钥存储:
- 国内合规场景下,用户 TOTP 密钥属于敏感个人信息,需加密落库(AES-256/GCM + 国密 SM4 可选),禁止明文;
- 推荐阿里云 KMS或腾讯云 KMS做信封加密,数据库只存密文密钥;
- 时间窗口与漂移:
- 国内移动网络延迟大,需支持**±1 周期(±30s)校验,且服务端时间必须通过 NTP 同步**,否则会出现批量校验失败;
- 防重放:
- 使用Redis Reactive(Lettuce)记录已用验证码,TTL 90s,Lua 脚本保证原子性“setnx + expire”;
- 用户体验:
- 首次绑定需展示Base32 二维码(谷歌 Authenticator、阿里钉钉均支持),二维码内容 = otpauth://totp/公司名:用户名?secret=XXX&issuer=公司名;
- 前端React/Vue通过WebSocket推送绑定结果,避免轮询。
答案
整体思路:**“Reactive 过滤器 → 异步校验 TOTP → 防重放 → 无状态会话”**四步闭环。
- 定义TOTP Reactive 服务
@Service
public class ReactiveTotpService {
private final ReactiveStringRedisTemplate redis;
private final SecretRepository secretRepo; // 自定义 Reactive MongoDB/R2DBC
public ReactiveTotpService(ReactiveStringRedisTemplate redis, SecretRepository secretRepo) {
this.redis = redis; this.secretRepo = secretRepo;
}
public Mono<Boolean> validate(String userId, String code) {
return secretRepo.findByUserId(userId) // 1. 取密钥
.publishOn(Schedulers.boundedElastic()) // 2. offload
.map(secret -> {
long current = System.currentTimeMillis() / 1000 / 30;
for (int i = -1; i <= 1; i++) { // 3. 漂移窗口
String expect = generateTotp(secret, current + i);
if (constantTimeEquals(code, expect)) {
return TOTP_OK;
}
}
return TOTP_FAIL;
})
.filter(r -> r == TOTP_OK)
.flatMap(r -> redis.opsForValue()
.setIfAbsent("totp:used:" + userId + ":" + code, "1", Duration.ofSeconds(90))
) // 4. 防重放
.hasElement(); // 有值说明校验+防重放都通过
}
private String generateTotp(String secretBase32, long timeWindow) {
byte[] decoded = Base32.decode(secretBase32);
byte[] timeBytes = new byte[8];
for (int i = 7; i >= 0; i--) { timeBytes[i] = (byte) (timeWindow & 0xff); timeWindow >>= 8; }
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(new SecretKeySpec(decoded, "HmacSHA1"));
byte[] hash = mac.doFinal(timeBytes);
int offset = hash[hash.length - 1] & 0x0f;
int binary = ((hash[offset] & 0x7f) << 24) |
((hash[offset + 1] & 0xff) << 16) |
((hash[offset + 2] & 0xff) << 8) |
(hash[offset + 3] & 0xff);
return String.format("%06d", binary % 1_000_000);
}
private boolean constantTimeEquals(String a, String b) { return MessageDigest.isEqual(a.getBytes(), b.getBytes()); }
}
- 定义Reactive 过滤器
@Component
public class TotpWebFilter implements WebFilter {
private final ReactiveTotpService totpService;
public TotpWebFilter(ReactiveTotpService totpService) { this.totpService = totpService; }
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
if (!request.getPath().value().equals("/api/totp/validate")) {
return chain.filter(exchange); // 非 TOTP 接口直接放行
}
String userId = exchange.getPrincipal() // 前置 JWT 登录已把 userId 放 Reactor Context
.cast(JwtAuthenticationToken.class)
.map(t -> t.getToken().getClaim("uid"))
.orElse("anonymous");
String code = request.getQueryParams().getFirst("code");
return totpService.validate(userId, code)
.flatMap(valid -> valid ? chain.filter(exchange)
: Mono.error(new ResponseStatusException(HttpStatus.UNAUTHORIZED, "TOTP 错误")));
}
}
- Security 配置
@EnableWebFluxSecurity
public class SecurityConfig {
@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http,
TotpWebFilter totpFilter) {
return http
.csrf().disable()
.addFilterAt(totpFilter, SecurityWebFiltersOrder.AUTHENTICATION + 100) // 插在 JWT 之后
.authorizeExchange(e -> e.pathMatchers("/api/totp/validate").authenticated()
.anyExchange().permitAll())
.build();
}
}
- 密钥绑定接口(首次扫码)
@RestController
@RequestMapping("/api/totp")
public class TotpSetupController {
@GetMapping(value = "/qrcode", produces = MediaType.IMAGE_PNG_VALUE)
public Mono<BufferedImage> qrCode(Principal principal) {
String userId = ((JwtAuthenticationToken) principal).getToken().getClaim("uid");
String secret = Base32.encode(RandomUtils.nextBytes(20));
return secretRepo.save(userId, secret) // 加密落库
.then(Mono.fromCallable(() -> {
String otpauth = "otpauth://totp/公司名:" + userId + "?secret=" + secret + "&issuer=公司名";
return QRCode.from(otpauth).stream().toImage(); // 使用 QRGen
}))
.subscribeOn(Schedulers.boundedElastic());
}
}
关键点总结:
- publishOn(boundedElastic()) 把 CPU 密集运算 offload,不阻塞 Netty EventLoop;
- Redis setIfAbsent 实现幂等校验,防重放攻击;
- JWT + Reactive Session 实现无状态横向扩展,满足大促流量;
- 密钥加密存储 + 国密可选,通过等保测评。
拓展思考
- 多因子叠加:
国内金融场景(支付、提现)要求三因子(密码 + TOTP + 人脸)。可在同一 Reactive 链路中串行调用人脸 RPC(基于 gRPC Reactive Stub),用 Reactor 的 zipWhen 合并结果,任何一步失败快速返回 Mono.error(),避免回调地狱。 - 冷启动性能优化:
大促零点瞬时 10w+ TOTP 校验,boundedElastic() 线程池可能打满。可预置本地缓存(Caffeine Reactive)存热点用户密钥,缓存命中率 80% 以上,Redis QPS 降 5 倍。 - 国密改造:
若客户为政府、央企,需把 HmacSHA1 换成 HmacSM3,Base32 换成 Base64 国密编码。Spring 侧只需替换 Mac 实例为 BouncyCastle SM3HMac,算法细节对外屏蔽,业务代码零改动。 - 审计与合规:
等保 2.0 要求失败记录留存 180 天。可异步发送 MQ(RocketMQ Reactive)审计事件,包含 userId、时间、IP、是否成功,消费端落 Elasticsearch,Kibana 仪表盘供公安部现场检查。