跳到主要内容
版本:7.0.2

WebSocket 安全

DeepSeek V3 中英对照 WebSocket Security

Spring Security 4.0+ 提供了对消息授权的支持。一个具体的应用场景是在基于 WebSocket 的应用程序中提供授权功能。

<websocket-message-broker>

websocket-message-broker 元素有两种不同的模式。如果未指定 websocket-message-broker@id,则它将执行以下操作:

  • 确保任何 SimpAnnotationMethodMessageHandler 都已将 AuthenticationPrincipalArgumentResolver 注册为自定义参数解析器。这允许使用 @AuthenticationPrincipal 来解析当前 Authentication 的主体。

  • 确保 SecurityContextChannelInterceptor 已自动注册到 clientInboundChannel。这会将 Message 中找到的用户信息填充到 SecurityContextHolder 中。

  • 确保 ChannelSecurityInterceptor 已注册到 clientInboundChannel。这允许为消息指定授权规则。

  • 确保 CsrfChannelInterceptor 已注册到 clientInboundChannel。这确保仅启用来自原始域的请求。

  • 确保 CsrfTokenHandshakeInterceptor 已注册到 WebSocketHttpRequestHandler、TransportHandlingSockJsService 或 DefaultSockJsService。这确保将来自 HttpServletRequest 的预期 CsrfToken 复制到 WebSocket 会话属性中。

若需进行额外控制,可指定id并为该id分配ChannelSecurityInterceptor。随后所有与Spring消息基础设施的关联配置均可手动完成。这种方式虽更繁琐,但能提供更精细的配置控制。

<websocket-message-broker> 属性

  • id Bean 标识符,用于在上下文中其他地方引用 ChannelSecurityInterceptor bean。如果指定,Spring Security 需要在 Spring Messaging 中进行显式配置。如果未指定,Spring Security 将自动与消息传递基础设施集成,如 <websocket-message-broker> 中所述。

  • same-origin-disabled 禁用要求在 Stomp 头信息中包含 CSRF 令牌(默认值为 false)。如果需要允许其他来源建立 SockJS 连接,更改此默认值会很有用。

  • authorization-manager-ref 使用此 AuthorizationManager 实例;设置此项时,use-authorization-manager 将被忽略并假定为 true

  • use-authorization-manager 使用 AuthorizationManager API 而非 SecurityMetadataSource API(默认为 true)。

  • security-context-holder-strategy-ref 使用此 SecurityContextHolderStrategy(注意:仅在与 AuthorizationManager API 结合使用时受支持)。

<websocket-message-broker> 的子元素

<intercept-message>

定义消息的授权规则。

<intercept-message> 的父元素

<intercept-message> 属性

  • pattern 基于Ant风格的消息目标匹配模式。例如,"/" 匹配所有具有目标地址的消息;"/admin/" 匹配所有目标地址以 "/admin/" 开头的消息。

  • type 要匹配的消息类型。有效值在 SimpMessageType 中定义(例如 CONNECT、CONNECT_ACK、HEARTBEAT、MESSAGE、SUBSCRIBE、UNSUBSCRIBE、DISCONNECT、DISCONNECT_ACK、OTHER)。

  • access 用于保护消息的访问控制表达式。例如,"denyAll" 将拒绝对所有匹配消息的访问;"permitAll" 将授予对所有匹配消息的访问权限;"hasRole('ADMIN')" 要求当前用户对匹配的消息拥有 'ROLE_ADMIN' 角色。