Spring Boot web service client authentication

In Spring Boot you are able to configure your beans with the @Bean annotation. You can use configuration classes for different beans. In those classes you need the @Configuaration annotation.

This tutorial describes the "second part" of the Spring tutorial. The main things of provided tutorial is: (based on the Spring tutorial)

The problem

The SOAP webservice I consume requires basic http authentication, so I need to add authentication header to the request.

Without authentication

First of all you need to have implemented a request without the authentication like in the tutorial on the spring.io. Then I will modify the http request with the authentication header.

Get the http request in custom WebServiceMessageSender

The raw http connection is accessible in the WeatherConfiguration class. There in the weatherClient you can set the message sender in the WebServiceTemplate. The message sender has access to the raw http connection. So now it’s time to extend the HttpUrlConnectionMessageSender and write custom implementation of it that will add the authentication header to the request. My custom sender is as follows:

public class WebServiceMessageSenderWithAuth extends HttpUrlConnectionMessageSender{

@Override
protected void prepareConnection(HttpURLConnection connection)
        throws IOException {

    BASE64Encoder enc = new sun.misc.BASE64Encoder();
    String userpassword = "yourLogin:yourPassword";
    String encodedAuthorization = enc.encode( userpassword.getBytes() );
    connection.setRequestProperty("Authorization", "Basic " + encodedAuthorization);

    super.prepareConnection(connection);
}

@Bean
public WeatherClient weatherClient(Jaxb2Marshaller marshaller){

WebServiceTemplate template = client.getWebServiceTemplate();
template.setMessageSender(new WebServiceMessageSenderWithAuth());

return client;
}