对于最新的稳定版本,请使用 Spring Security 6.5.3! |
WebSocket 安全性
Spring Security 4.0+ 提供对授权消息的支持。 这有用的一个具体示例是在基于 WebSocket 的应用程序中提供授权。
<websocket-message-broker >
websocket-message-broker 元素有两种不同的模式。 如果未指定 websocket-message-broker@id,则它将执行以下作:
-
确保任何 SimpAnnotationMethodMessageHandler 都已将 AuthenticationPrincipalArgumentResolver 注册为自定义参数解析器。 这允许使用
@AuthenticationPrincipal
解决当前Authentication
-
确保 SecurityContextChannelInterceptor 自动注册给 clientInboundChannel。 这会使用 Message 中找到的用户填充 SecurityContextHolder
-
确保向 clientInboundChannel 注册 ChannelSecurityInterceptor。 这允许为消息指定授权规则。
-
确保向 clientInboundChannel 注册 CsrfChannelInterceptor。 这可确保仅启用来自原始域的请求。
-
确保向 WebSocketHttpRequestHandler、TransportHandlingSockJsService 或 DefaultSockJsService 注册 CsrfTokenHandshakeInterceptor。 这可确保将 HttpServletRequest 中的预期 CsrfToken 复制到 WebSocket 会话属性中。
如果需要其他控制,可以指定 ID,并将 ChannelSecurityInterceptor 分配给指定的 ID。 然后,所有与 Spring 消息传递基础设施的连接都可以手动完成。 这更麻烦,但提供了对配置的更好控制。
<websocket-message-broker> 属性
-
id 一个 bean 标识符,用于引用上下文中其他地方的 ChannelSecurityInterceptor bean。 如果指定,Spring Security 需要在 Spring Messaging 中进行显式配置。 如果未指定,Spring Security将自动与消息传递基础结构集成,如<websocket-message-broker中所述>
-
同源禁用禁用 Stomp 标头中存在 CSRF Tokens的要求(默认为 false)。 如果需要允许其他源建立 SockJS 连接,则更改默认值很有用。
-
安全上下文-持有者-策略-引用使用这个
SecurityContextHolderStrategy
(注意仅支持与AuthorizationManager
API)
<拦截消息>
定义消息的授权规则。
<intercept-message> 属性
-
模式在消息目标上匹配的基于Ant的模式。 例如,“/”匹配任何具有目标的消息;/admin/“匹配目标以”/admin/**“开头的任何消息。
-
类型要匹配的消息类型。 有效值在 SimpMessageType 中定义(即 CONNECT、CONNECT_ACK、HEARTBEAT、MESSAGE、SUBSCRIBE、UNSUBSCRIBE、DISCONNECT、DISCONNECT_ACK、OTHER)。
-
访问用于保护消息的表达式。 例如,“denyAll”将拒绝访问所有匹配的消息;“permitAll”将授予对所有匹配消息的访问权限;“hasRole('ADMIN') 要求当前用户具有匹配消息的”ROLE_ADMIN“角色。