Http Basic Authentication not working with Spring WS and WebServiceTemplate credentials
11,403
Solution 1
I had similar problem and this article helped me: https://looksok.wordpress.com/2014/09/06/spring-4-soap-request-with-http-basic-authentication/
Solution 2
As described on this link (thank you @Milos), you need to create a class:
public class WebServiceMessageSenderWithAuth extends HttpUrlConnectionMessageSender{
@Override
protected void prepareConnection(HttpURLConnection connection)
throws IOException {
Base64.Encoder enc = Base64.getEncoder();
String userpassword = "login:password"; // change to a real user and password
String encodedAuthorization = enc.encodeToString(userpassword.getBytes());
connection.setRequestProperty("Authorization", "Basic " + encodedAuthorization);
super.prepareConnection(connection);
}
}
And pass to message sender method:
setMessageSender(new WebServiceMessageSenderWithAuth());
Comments
-
dexBerlin almost 2 years
I try to add HTTP Basic Auth credentials to my SOAP-Request using Spring(-WS). The Request itself works, but no credentials are submitted. The HTTP header should look like:
[...] Connection: Keep-Alive User-Agent: Apache-HttpClient/4.1.1 (java 1.5) Authorization: Basic mybase64encodedtopsecretcredentials=
But the last row is not missing. In MyConfig.java, I configure the Bean (no XML):
@Bean public WebServiceTemplate webServiceTemplate() { WebServiceTemplate template = new WebServiceTemplate(); try { template.setMarshaller(marshaller()); //Jaxb2Marshaller template.setUnmarshaller(marshaller()); // proxy for tcpmon inspection template.setDefaultUri("http://127.0.0.1:29080/target/webservice.php"); String username = environment.getProperty("config.username"); String password = environment.getProperty("config.password"); Credentials credentials = new UsernamePasswordCredentials(username, password); HttpComponentsMessageSender sender = new HttpComponentsMessageSender(); sender.setCredentials(credentials); sender.afterPropertiesSet(); template.setMessageSender(sender); } catch (Exception e) { // @todo: handle me } return template; }
If you know the reason why the Authorization line is missing, please let me know. :) Thank you a lot in advance