WebSocket 安全

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,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”角色。

© . This site is unofficial and not affiliated with VMware.