Search code examples
springspring-integrationspring-ws

Spring Global ClientInterceptor


I have a legacy application that consumes lots of customer services. Lately, it is required to add a custom http security header per request. One way is to add a ClientInterceptor per WebServiceTemplate but I feel like it is a bit code repeat. Is there a way to apply a global ClientInterceptor ?

As I said this is a legacy system which is still built on top of Spring Fw 3.2.2.RELEASE and spring-ws 2.0.6-RELEASE


Solution

  • You can implement a general ClientInterceptor, something like this:

    public class AddCustomSecurityHeader implements ClientInterceptor {
    
        @Override
        public boolean handleRequest(MessageContext messageContext) throws WebServiceClientException {
           TransportContext context = TransportContextHolder.getTransportContext();
           HttpComponentsConnection connection =(HttpComponentsConnection) context.getConnection();
           connection.addRequestHeader("custom-security-header", "lorem ipsum");
    
           return true;
        }
    }
    

    Then you declare a @Bean of type WebServiceTemplate:

    @Bean
    public WebServiceTemplate webServiceTemplate() {
        WebServiceTemplate webServiceTemplate = new WebServiceTemplate();
        // add your current configuration here
    
        ClientInterceptor[] interceptors = {new AddCustomSecurityHeader()};
        webServiceTemplate.setInterceptors(interceptors);
        return webServiceTemplate;
    }
    

    I hope it helps!