此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Security 6.4.1spring-doc.cadn.net.cn

WebSocket 安全性

Spring Security 4.0+ 提供了对授权消息的支持。 一个有用的具体示例是在基于 WebSocket 的应用程序中提供授权。spring-doc.cadn.net.cn

<websocket-消息代理>

websocket-message-broker 元素有两种不同的模式。 如果未指定 websocket-message-broker@id,则它将执行以下作:spring-doc.cadn.net.cn

  • 确保任何SimpAnnotationMethodMessageHandler都已将AuthenticationPrincipalArgumentResolver注册为自定义参数解析器。 这允许使用@AuthenticationPrincipal解析当前Authenticationspring-doc.cadn.net.cn

  • 确保SecurityContextChannelInterceptor自动为clientInboundChannel注册。 这将使用在 Message 中找到的用户填充 SecurityContextHolderspring-doc.cadn.net.cn

  • 确保ChannelSecurityInterceptor已注册到clientInboundChannel中。 这允许为消息指定授权规则。spring-doc.cadn.net.cn

  • 确保 CsrfChannelInterceptor 已向 clientInboundChannel 注册。 这可确保仅启用来自原始域的请求。spring-doc.cadn.net.cn

  • 确保 CsrfTokenHandshakeInterceptor 已向 WebSocketHttpRequestHandler、TransportHandlingSockJsService 或 DefaultSockJsService 注册。 这可确保将 HttpServletRequest 中预期的 CsrfToken 复制到 WebSocket Session 属性中。spring-doc.cadn.net.cn

如果需要额外的控制,可以指定 id,并将 ChannelSecurityInterceptor 分配给指定的 id。 然后,可以手动完成与 Spring 消息传递基础结构的所有连接。 这更麻烦,但提供了对配置的更大控制。spring-doc.cadn.net.cn

<websocket-message-broker> 属性

  • id 一个 Bean 标识符,用于在上下文中其他位置引用ChannelSecurityInterceptor Bean。 如果指定,则 Spring Security 需要在 Spring Messaging 中进行显式配置。 如果未指定,Spring Security 将自动与消息传递基础结构集成,如<websocket-message-broker中所述>spring-doc.cadn.net.cn

  • 同源已禁用禁用 Stomp 标头中存在 CSRF 令牌的要求(默认为 false)。 如果需要允许其他源进行 Sockjs 连接,则更改默认值非常有用。spring-doc.cadn.net.cn

  • 授权管理器引用使用这个AuthorizationManager实例;设置后,use-authorization-manager被忽略并假定为truespring-doc.cadn.net.cn

  • 使用授权管理器AuthorizationManagerAPI 而不是SecurityMetadataSourceAPI (默认为 true)。spring-doc.cadn.net.cn

  • security-context-holder-strategy-ref (安全上下文持有者策略引用)使用这个SecurityContextHolderStrategy(注意:仅支持与AuthorizationManagerAPI 的 APIspring-doc.cadn.net.cn

<拦截消息>

定义消息的授权规则。spring-doc.cadn.net.cn

<intercept-message 的父元素>

<intercept-message> 属性

  • 模式与 Message 目标匹配的基于 ant 的模式。 例如,“/” 匹配任何具有目标的 Message;/admin/“ 匹配目标以 ”/admin/**“ 开头的任何消息。spring-doc.cadn.net.cn

  • 类型要匹配的消息类型。 有效值在 SimpMessageType 中定义(即 CONNECT、CONNECT_ACK、HEARTBEAT、MESSAGE、SUBSCRIBE、UNSUBSCRIBE、DISCONNECT、DISCONNECT_ACK、OTHER)。spring-doc.cadn.net.cn

  • 访问用于保护 Message 的表达式。 例如,“denyAll” 将拒绝对所有匹配 Message 的访问;“permitAll” 将授予对所有匹配 Message 的访问权限;“hasRole('ADMIN') 要求当前用户具有匹配消息的角色 'ROLE_ADMIN'。spring-doc.cadn.net.cn