WebSocket 安全

Spring Security 4.0+ 支持对消息进行授权。一个具体的使用示例是在基于 WebSocket 的应用程序中提供授权。

<websocket-message-broker>

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

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

  • 确保 SecurityContextChannelInterceptor 自动注册到 clientInboundChannel。这将使用消息中找到的用户填充 SecurityContextHolder

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

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

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

如果需要额外的控制,可以指定 id,并且 ChannelSecurityInterceptor 将被分配给指定的 id。然后可以手动完成与 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'。