使用 Spring Security 保护 STOMP 端点
学习如何在 Spring 中对 STOMP 消息进行身份验证和授权,保护握手、目标地址和面向用户的消息,防止未经授权的访问。
使用 Spring Security 保护 STOMP 端点 是 CoddyKit 上的免费 WebSockets & Real-Time Systems with Spring 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 WebSockets & Real-Time Systems with Spring 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 WebSockets & Real-Time Systems with Spring 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Why Secure STOMP?
An open STOMP endpoint lets anyone subscribe to and publish on any destination. Securing STOMP ensures only authenticated users connect and only authorized users access specific destinations.
This lesson layers Spring Security onto STOMP messaging.
Two Layers of Security
STOMP security operates at two levels:
- Handshake: authenticate the user when the WebSocket connection opens
- Message: authorize each SUBSCRIBE and SEND to a destination
Both layers are needed for real protection.
Authenticating the Handshake
The connection should carry the user's identity. With session-based auth, Spring Security propagates the HTTP session principal into the WebSocket session automatically.
Token Auth on CONNECT
For token-based auth, read the token from the STOMP CONNECT frame headers using a ChannelInterceptor and set the authenticated principal on the message.
@Override
public Message<?> preSend(Message<?> message, MessageChannel channel) {
StompHeaderAccessor acc = StompHeaderAccessor.wrap(message);
if (StompCommand.CONNECT.equals(acc.getCommand())) {
String token = acc.getFirstNativeHeader('Authorization');
Authentication user = tokenService.validate(token);
acc.setUser(user);
}
return message;
}Authorizing Destinations
Spring provides AbstractSecurityWebSocketMessageBrokerConfigurer to define which roles may access which destinations, similar to HTTP security rules.
@Override
protected void configureInbound(MessageSecurityMetadataSourceRegistry messages) {
messages
.simpDestMatchers('/app/admin/**').hasRole('ADMIN')
.simpSubscribeDestMatchers('/topic/public').permitAll()
.anyMessage().authenticated();
}Per-User Destinations
The /user/** prefix routes messages to a single user's private queue. Spring resolves these against the authenticated principal, so users only receive their own messages.
// Server side: send to a specific user
messagingTemplate.convertAndSendToUser(
username, '/queue/notifications', payload);CSRF Considerations
The WebSocket handshake is an HTTP request and can be subject to CSRF. Validate origins and, where applicable, require a CSRF token so attackers cannot open connections from malicious pages.
Restricting Origins
Always lock down allowed origins for the STOMP endpoint. An open origin policy lets any website connect on behalf of a logged-in user.
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint('/ws')
.setAllowedOrigins('https://app.example.com')
.withSockJS();
}Validating Message Payloads
Authentication is not enough; validate the content of every message. Reject oversized payloads, unexpected fields, and malformed data to prevent injection and resource exhaustion.
- Enforce size limits
- Validate against a schema
- Reject unknown destinations
Logging Security Events
Log failed connections, denied subscriptions, and authorization failures. These events feed monitoring and help detect abuse or probing of your messaging layer.
Defense in Depth
Combine handshake auth, destination authorization, origin restriction, and payload validation. No single control is sufficient; layered controls keep your real-time messaging secure even if one fails.
Quick Check
Test your understanding of STOMP security.
Recap
You learned to secure STOMP at two layers: authenticate the handshake (session or token), then authorize destinations with Spring Security rules. Per-user destinations, origin restrictions, payload validation, and event logging together provide defense in depth for real-time messaging.
常见问题解答
「使用 Spring Security 保护 STOMP 端点」课时是免费的吗?
是的 — 「使用 Spring Security 保护 STOMP 端点」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 WebSockets & Real-Time Systems with Spring 课程的其余内容,请升级到 CoddyKit PRO。 WebSockets & Real-Time Systems with Spring 课程共包含 4 节课。
「使用 Spring Security 保护 STOMP 端点」这节课中我会学到什么?
学习如何在 Spring 中对 STOMP 消息进行身份验证和授权,保护握手、目标地址和面向用户的消息,防止未经授权的访问。 你通过在浏览器中直接运行的动手代码来练习 WebSockets & Real-Time Systems with Spring,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 WebSockets & Real-Time Systems with Spring 需要有经验吗?
无需任何先前经验。CoddyKit 上的 WebSockets & Real-Time Systems with Spring 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「使用 Spring Security 保护 STOMP 端点」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 WebSockets & Real-Time Systems with Spring 课中编写并运行代码吗?
能。每节 WebSockets & Real-Time Systems with Spring 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- STOMP 协议简介
- 使用 Spring 配置 STOMP
- 发送和接收 STOMP 消息
- 使用 Spring Security 保护 STOMP 端点