WebSocket 安全性

Spring Security 4.0+ 提供了授權訊息的支援。其中一個具體的應用範例是在基於 WebSocket 的應用程式中提供授權。

<websocket-message-broker>

websocket-message-broker 元素有兩種不同的模式。如果未指定 websocket-message-broker@id,則它將執行以下操作

  • 確保任何 SimpAnnotationMethodMessageHandler 都已註冊 AuthenticationPrincipalArgumentResolver 作為自訂引數解析器。這允許使用 @AuthenticationPrincipal 來解析當前 Authentication 的 Principal。

  • 確保 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" 角色。