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 連線,更改此預設值很有用。
-
security-context-holder-strategy-ref 使用此
SecurityContextHolderStrategy
(注意僅與AuthorizationManager
API 結合使用時支援)
<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'。