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 連線,更改預設值很有用。
-
security-context-holder-strategy-ref 使用此
SecurityContextHolderStrategy(請注意,僅與AuthorizationManagerAPI 結合使用才支援)。
<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”角色。