配置 RSocket over WebSocket 并启用 JWT 认证拦截器
解读
在国内互联网面试中,RSocket 作为“背压感知、异步、多路复用”的 Reactive 通信协议,常被用来考察候选人对 高并发、低延迟、云原生 场景的落地能力。
题目要求“RSocket over WebSocket + JWT 认证拦截器”,本质是验证三件事:
- 能否把 RSocket 帧 透传在 WebSocket 二进制帧 之上,解决防火墙/网关穿透问题;
- 能否利用 Spring Security 5.x RSocket 模块 的
PayloadInterceptor链,把无状态的 JWT 认证逻辑插进去; - 能否在 Spring Boot 自动装配 之外,手写
RSocketMessageHandler与SocketAcceptorInterceptor的 Bean 定义,做到“零 XML、全 Java、可插拔”。
面试官通常会追问:
- JWT 过期后怎样在 Reactive 流 中触发重认证而不断链?
- 如何在 Netty 层 自定义 WebSocket 子协议协商?
- 与 Spring Cloud Gateway 的 RSocket 路由 如何联动?
因此,答案必须体现“协议栈穿透 + 安全拦截 + 高可用”三板斧。
知识点
- RSocket 四种交互模型:Fire-and-Forget、Request/Response、Request-Stream、Channel;
- WebSocket 子协议:
rsocket.websocket的MimeType必须是application/vnd.rsocket.websocket; - JWT 在 RSocket 中的载体:只能放在 CompositeMetadata 的
BearerTokenMetadata.BEARER_AUTHENTICATION_MIME_TYPE(message/x.rsocket.authentication.bearer.v0); - Spring Security RSocket 核心类:
PayloadInterceptor→AuthenticationPayloadInterceptorReactiveAuthenticationManager→JwtReactiveAuthenticationManagerRSocketSecurity→authorizePayload的route级 DSL;
- Netty 层配置:
ReactorNettyTcpClient的websocketSubprotocols("v1.rsocket.websocket"); - Spring Boot 装配顺序:
RSocketServerCustomizer>RSocketMessageHandler>SocketAcceptorInterceptor,必须显式@Order防止被 actuator 覆盖; - 国产网关适配:阿里 SCA 2021.x 分支已支持 RSocket 路由,但需把 JWT 放在 GatewayFilter 的
RSocketRequesterheader 中,避免二次解码。
答案
(以下代码基于 Spring Boot 2.7.x + Spring Security 5.7.x,JDK 11,Maven 依赖已排除 spring-boot-starter-web,仅保留 spring-boot-starter-rsocket 与 spring-security-rsocket)
- 引入坐标
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-rsocket</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-rsocket</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>
- 在
application.yml中开启 WebSocket 端口
spring:
rsocket:
server:
port: 7000
transport: websocket
mapping-path: /rsocket
- JWT 资源服务器配置(国产场景通常使用 自研 SSO 颁发的 JWT,公钥通过 nacos 配置中心 热更新)
@Configuration
@EnableWebFluxSecurity
public class JwtConfig {
@Value("${jwt.public-key}")
private RSAPublicKey key;
@Bean
public ReactiveJwtDecoder jwtDecoder() {
return NimbusReactiveJwtDecoder.withPublicKey(key).build();
}
@Bean
public ReactiveAuthenticationManager authenticationManager(ReactiveJwtDecoder decoder) {
return new JwtReactiveAuthenticationManager(decoder);
}
}
- RSocket 安全拦截器(核心考点)
@Configuration
public class RSocketSecurityConfig {
@Bean
public RSocketSecurity rsocketSecurity(ReactiveAuthenticationManager manager) {
return RSocketSecurity.create()
.authorizePayload(spec -> spec
.route("api.v1.**").authenticated()
.anyExchange().permitAll())
.jwt(Customizer.withDefaults())
.authenticationManager(manager);
}
@Bean
public SocketAcceptorInterceptor interceptor(RSocketSecurity security) {
return security.interceptor();
}
}
- 服务端 Handler(暴露 Request-Stream 接口)
@Controller
public class StreamController {
@MessageMapping("api.v1.stream")
public Flux<String> stream(@AuthenticationPrincipal Jwt jwt) {
String uid = jwt.getClaimAsString("uid");
return Flux.interval(Duration.ofSeconds(1))
.map(i -> "msg#" + i + " for " + uid);
}
}
- 客户端启动器(用于自测,WebSocket 连接串 为
ws://localhost:7000/rsocket)
RSocketRequester requester = RSocketRequester.builder()
.rsocketStrategies(strategies -> strategies
.encoder(new BearerTokenAuthenticationEncoder()))
.setupMetadata("eyJ0eXAiOiJKV1QiLCJhbGc...", BearerTokenMetadata.BEARER_AUTHENTICATION_MIME_TYPE)
.websocket(URI.create("ws://localhost:7000/rsocket"));
- 验证步骤
- 启动应用,查看 Netty 日志出现
WebSocket subprotocol selected: v1.rsocket.websocket; - 使用 Postman 或 rsc-cli 带 JWT 调用,返回
200流式数据; - 把 JWT 篡改,服务端立即返回
ERROR[0x00000301]: Access Denied,证明拦截器生效。
拓展思考
- 双 Token 无感刷新:在 Reactive 流 中捕获
JwtException,通过Sinks.Many向客户端推送REFRESH_REQUIRED自定义帧,客户端用 RefreshToken 重新获取 AccessToken 后 resume 流,而不是重连 TCP; - 灰度路由:结合 Spring Cloud LoadBalancer 把 JWT 中的
tag=gray解析成 RSocket 的RoutingMetadata,实现同一套接口 多版本并行; - 性能调优:Netty 层开启 WebsocketCompressionServerExtension,在 4C8G 容器下 QPS 可提升 18%;
- 国密算法:若甲方要求 SM2/SM3,可自定义
ReactiveJwtDecoder调用 江南天安 或 北京数字认证 的 SDK,把公钥接口封装成NimbusReactiveJwtDecoder的JwtProcessor; - 监控埋点:通过 Micrometer RSocket Metrics 把
rsocket.status与jwt.auth.failure指标打入 Prometheus + Grafana,配合 阿里 SLS 做告警,满足国内等保 2.0 审计要求。