Tengo una aplicación donde necesito dos configuraciones diferentes de websocket:
Ahora, en Spring, para deshabilitar la verificación de orígenes cruzados para websockets, es necesario extender AbstractSecurityWebSocketMessageBrokerConfigurer , por ejemplo, de la siguiente manera:
@Configuration public class WebSocketSecurityConfig extends AbstractSecurityWebSocketMessageBrokerConfigurer { @Override protected void configureInbound(final MessageSecurityMetadataSourceRegistry messages) { messages.anyMessage().authenticated(); } @Override protected boolean sameOriginDisabled() { return true; } }La pregunta es, ¿cómo puedo desactivarlo para algunos websockets y habilitarlo para otros?
Si echa un vistazo al método AbstractSecurityWebSocketMessageBrokerConfigurer#configureClientInboundChannel(ChannelRegistration) , cuando tiene sameOriginDisabled establecido en false , simplemente registra un CsrfChannelInterceptor :
if (!sameOriginDisabled()) { registration.setInterceptors(this.context.getBean(CsrfChannelInterceptor.class)); } Y después de eso, llama al método customizeClientInboundChannel(ChannelRegistration) .
No puedo probar ahora, pero creo que puede anular el método customizeClientInboundChannel(ChannelRegistration) y hacer lo siguiente:
@Override protected void customizeClientInboundChannel(ChannelRegistration registration) { registration.addInterceptor(myCustomCsrfChannelInterceptor()); } private CsrfChannelInterceptor myCustomCsrfChannelInterceptor() { return new MyCustomCsrfChannelInterceptor(); } private static class MyCustomCsrfChannelInterceptor { private MessageMatcher<Object> matcher = //create your MessageMatcher with your rules @Override public Message<?> preSend(Message<?> message, MessageChannel channel) { if (!this.matcher.matches(message)) { return message; } //copy the content from `CsrfChannelInterceptor` } } En resumen, lo que está haciendo es crear un CsrfChannelInterceptor personalizado que usará un MessageMatcher personalizado con sus propias reglas para verificar si debe aplicarse a ese Message , y el resto es solo una copia del interceptor original.