HTTP Basic Authentication in Java SOAP JAX-WS web service client

1 minute read

Today I had to create a Java client for a SOAP web service. So I opened Netbeans IDE and used the great tool which generates JAX-WS client code using the respective service .wsdl file. However, the service needed to be called using Basic Http Authentication.

NOTE: The solution provided works if the WSDL is not protected itself by Basic Http Authentication. The Basic Authentication is added as a header in the HTTP request.

After a lot of searching I found that (StackOverflow question) this is possible:

ContactCreationRequestService_Service srv = new ContactCreationRequestService_Service();
ContactCreationRequestService porta ;

// Get service port
try {
    porta = srv.getContactCreationRequestServicePort();
}catch (Exception e){
    logger.error(e);
    return;
}

// Add username and password for Basic Authentication
Map<String, Object> reqContext = ((BindingProvider) porta).getRequestContext();
reqContext.put(BindingProvider.USERNAME_PROPERTY, "username");
reqContext.put(BindingProvider.PASSWORD_PROPERTY, "password");

// Create a contact request
ContactRequest ka = new ContactRequest();
ka.setPrefix("Mr");
ka.setName("Christos");
ka.setSurname("Manios");

NewContact nka = new NewContact();
nka.setContactRequest(ka);

// Call the web service
try {
    porta.newContactCreationRequest(nka);
} catch (SoapServiceException e) {
    logger.error(e);
}

If we enable debugging to see the actual HTTP request, then the logs will show output like the following:

---[HTTP request - http://localhost:9090/ContactRequestServicePort]---
Accept: text/xml, multipart/related
Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=
Content-Type: text/xml; charset=utf-8
SOAPAction: "newContact"
User-Agent: JAX-WS RI 2.2.9-b130926.1035 svn-revision#5f6196f2b90e9460065a4c2f4e30e065b245e51e
<?xml version="1.0" ?><S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"><S:Body><ns2:newContact xmlns:ns4="http://www.acmecorp.com/contacts/Exception" xmlns:ns3="http://www.acmecorp.com/contacts/RequestMetaInfo" xmlns:ns2="http://www.acmecorp.com/contacts/crm-contact/Service"><ns2:contact><ns2:prefix>Mr</ns2:prefix><ns2:name>John</ns2:name><ns2:surname>Longjohn</ns2:surname></ns2:contact></ns2:newContact></S:Body></S:Envelope>--------------------

You can observe that the request contains the Authorization header as expected:

Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=

Comments