My goal is to call web service, which is require authentification (when I opne it's wsdl in my browser, browser asks me login+password).
As a base, I use the sample from this tutorial.
And now I have to add authentification configurations.
Accoding to the documentation something like configuring WebServiceTemplate bean may help.
But with Spring Boot there are no applicationContext.xml or any other configuration xml's in a project.
So, how to configure WebServiceTemplate using Spring Boot, or what else can solve such task?
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;
}