在 WebFlux 中如何自定义 ReactiveRealm 连接 R2DBC?

解读

国内主流 Spring Cloud 微服务已大量迁移到 响应式 WebFlux 容器,而 Shiro 1.x 默认只提供阻塞式 JDBC Realm。面试官真正想确认的是:

  1. 你是否理解 Reactive 线程模型(EventLoop 线程不能阻塞);
  2. 能否把 Shiro 的认证/授权逻辑也做成 非阻塞;
  3. 是否熟悉 R2DBC 驱动与 Spring Data R2DBC 的响应式 API;
  4. 最终让 SecurityManager 在 WebFlux 环境下 零阻塞地读取数据库。

答不出“自定义 ReactiveRealm”就等于承认只能在 WebFlux 里混用阻塞代码,直接 降分。

知识点

  1. ReactiveRealm 接口:Shiro 1.8+ 新增,唯一抽象方法 Mono<AuthenticationInfo> doGetAuthenticationInfo(AuthenticationToken token),全程返回 Reactor Mono/Flux。
  2. R2DBC 核心 API:DatabaseClient / R2dbcEntityTemplate / 自定义 ReactiveCrudRepository,返回类型必须是 Mono<T> 或 Flux<T>。
  3. 密码比对策略:Shiro 提供的 HashedCredentialsMatcher 是阻塞实现,必须在 ReactiveRealm 里 手动调用 new Sha256Hash(password, salt, 1024).toHex() 做哈希,再用 Mono.just(encodedPassword).map(...) 比对,避免同步阻塞。
  4. 缓存与上下文:WebFlux 默认不使用 HttpSession,需要把 授权信息缓存 放到 ReactiveRedisCache 或 CaffeineAsyncCache,并通过 SecurityUtils.setSecurityManager(reactiveSecurityManager) 绑定到 Reactor 上下文。
  5. 事务边界:R2DBC 事务由 TransactionalOperator 或 @Transactional(reactive = true) 控制,认证/授权 SQL 必须在一个 只读事务 内完成,防止长连接泄漏。

答案

  1. 引入依赖
<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-spring-boot-web-starter</artifactId>
    <version>1.12.0</version>
    <exclusions>
        <!-- 排除阻塞 Web 模块 -->
        <exclusion>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-web</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-reactive-web</artifactId>
    <version>1.12.0</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-r2dbc</artifactId>
</dependency>
<dependency>
    <groupId>io.asyncer</groupId>
    <artifactId>r2dbc-mysql</artifactId>
    <version>1.0.5</version>
</dependency>
  1. 自定义 ReactiveRealm
@Component
public class R2dbcReactiveRealm extends AuthorizingRealm implements ReactiveRealm {

    private final DatabaseClient client;
    private final ReactiveRedisCacheManager cacheManager;

    public R2dbcReactiveRealm(DatabaseClient client,
                              ReactiveRedisCacheManager cacheManager) {
        this.client = client;
        this.cacheManager = cacheManager;
        // 关闭阻塞的 CredentialsMatcher,改用 Reactive 手动比对
        setCredentialsMatcher((token, info) -> true);
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof UsernamePasswordToken;
    }

    /* ====== ReactiveRealm 接口 ====== */
    @Override
    public Mono<AuthenticationInfo> doGetAuthenticationInfo(AuthenticationToken token) {
        String username = (String) token.getPrincipal();
        String password = new String((char[]) token.getCredentials());

        return client.sql("SELECT id, password, salt FROM t_user WHERE username = :u")
                     .bind("u", username)
                     .map(row -> new UserRow(
                             row.get("id", Long.class),
                             row.get("password", String.class),
                             row.get("salt", String.class)))
                     .one()
                     .switchIfEmpty(Mono.error(new UnknownAccountException("用户不存在")))
                     .flatMap(u -> {
                         String hashed = new Sha256Hash(password, u.salt(), 1024).toHex();
                         if (!u.password().equals(hashed)) {
                             return Mono.error(new IncorrectCredentialsException("密码错误"));
                         }
                         SimpleAuthenticationInfo info =
                                 new SimpleAuthenticationInfo(u.id(), password, getName());
                         return Mono.just(info);
                     });
    }

    /* ====== 授权 ====== */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        // 阻塞方法不会被调用;Shiro 会走 ReactiveAuthorizingSessionStorage
        return null;
    }

    public Mono<AuthorizationInfo> doGetAuthorizationInfoReactive(PrincipalCollection principals) {
        Long userId = (Long) principals.getPrimaryPrincipal();
        return cacheManager.getCache("shiro-auth-cache")
                           .get(userId, AuthorizationInfo.class)
                           .switchIfEmpty(
                               Flux.merge(
                                   client.sql("SELECT role_code FROM t_user_role WHERE user_id = :id")
                                         .bind("id", userId)
                                         .map(row -> row.get("role_code", String.class))
                                         .all(),
                                   client.sql("SELECT permission_code FROM t_user_permission WHERE user_id = :id")
                                         .bind("id", userId)
                                         .map(row -> row.get("permission_code", String.class))
                                         .all())
                               .collectList()
                               .map(list -> {
                                   SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
                                   list.stream()
                                       .filter(s -> s.startsWith("ROLE_"))
                                       .forEach(info::addRole);
                                   list.stream()
                                       .filter(s -> !s.startsWith("ROLE_"))
                                       .forEach(info::addStringPermission);
                                   return info;
                               })
                               .flatMap(auth -> cacheManager.getCache("shiro-auth-cache")
                                                             .put(userId, auth)
                                                             .thenReturn(auth))
                           );
    }
}
  1. 装配 ReactiveSecurityManager
@Configuration
@AutoConfigureAfter(ShiroReactiveWebAutoConfiguration.class)
public class ShiroReactiveConfig {

    @Bean
    public ReactiveSecurityManager reactiveSecurityManager(R2dbcReactiveRealm realm) {
        DefaultReactiveSecurityManager sm = new DefaultReactiveSecurityManager();
        sm.setRealm(realm);
        // 关闭默认的阻塞 SessionDAO
        sm.setSessionManager(new ReactiveWebSessionManager());
        return sm;
    }

    @Bean
    public ShiroFilterChainDefinition shiroFilterChainDefinition() {
        DefaultShiroFilterChainDefinition chain = new DefaultShiroFilterChainDefinition();
        chain.addPathDefinition("/login", "anon");
        chain.addPathDefinition("/**", "authc");
        return chain;
    }
}
  1. 登录端点(完全非阻塞)
@RestController
@RequestMapping
public class LoginController {

    @PostMapping("/login")
    public Mono<Void> login(@RequestBody LoginDTO dto, ServerWebExchange exchange) {
        UsernamePasswordToken token =
                new UsernamePasswordToken(dto.getUsername(), dto.getPassword());
        return SecurityUtils.getSubject()
                            .login(token)   // 内部会调用 ReactiveRealm
                            .then(exchange.getResponse().setComplete());
    }
}

至此,整个认证与授权链路全部基于 R2DBC + Reactor,无阻塞、无 JDBC、无 Tomcat 线程池等待,符合国内互联网高并发场景对 WebFlux 全栈响应式 的硬性要求。

拓展思考

  1. 性能调优:R2DBC 连接池务必使用 r2dbc-pool,默认最大连接数 10 在双十一流量下会瞬间打满,建议动态配置 initialSize=20|maxSize=200|maxIdleTime=30s,并通过 ConnectionFactoryOptions 开启 native epoll 在 Linux 环境获得 15% 以上吞吐提升。
  2. 多租户 SaaS:在 ReactiveRealm 里增加 Mono<String> tenantId = ReactiveSecurityContextHolder.getContext().getAuthentication().getDetails(),把 tenant_id 作为 SQL 绑定参数,实现 同库分表 的租户隔离,避免不同租户缓存穿透。
  3. 密码升级:国内等保 2.0 要求 SM3 国密算法,可自定义 Sm3Hash 替换 Sha256Hash,但需保证 Sm3Hash 内部无阻塞随机数;或者把哈希计算丢到 并行调度器 Schedulers.parallel(),防止 EventLoop 被占用。
  4. 审计日志:响应式链路不能直接用 MDC,需要借助 Reactor Context 传递 traceId,通过 WebFilter 把日志写到 Kafka Reactive Producer,再落 Elasticsearch;面试时可主动提及,展示你对 全链路观测 的落地经验。