Wednesday, January 30, 2013

JAX-WS webservice client basic authentication

JAX-WS webservice client basic authentication:


Sometimes we may need to create a webservice client for a JAX-WS webservice that require the basic authentication.
This post will explain the how to pass the username/password when invoking the basic authentication enabled web services from the client.

Java client with basic authentication details:

import java.util.*;
import javax.xml.ws.*;
import weblogic.wsee.security.unt.ClientUNTCredentialProvider;
import weblogic.xml.crypto.wss.WSSecurityContext;
import weblogic.xml.crypto.wss.provider.CredentialProvider;

public class DataObjectOperationsByNameClient
{
  @WebServiceRef
  private static DataObjectOperationsByName_Service dataObjectOperationsByName_Service;
  public static void main(String [] args)
  {
    dataObjectOperationsByName_Service = new DataObjectOperationsByName_Service();
    DataObjectOperationsByName dataObjectOperationsByName = dataObjectOperationsByName_Service.getDataObjectOperationsByName();
    String input="<DataObject Name=\"BAMWebservice\" Path=\"/Albin\">\n" + "<Contents>\n" + "<Row>\n" + "<Column Name=\"Field1\" Value=\"Albin\" />\n" +
    "<Column Name=\"Field2\" Value=\"I.T\" />\n" +"<column Name=\"Field3\" Value=\"TR\" />\n" +"</Row>\n" + "</Contents>\n" + "</DataObject>\n";   
      String USERNAME = "weblogic";
      String PASSWORD = "welcome1";
        try {
            BindingProvider bindingProvider = (BindingProvider) dataObjectOperationsByName;
            Map<String,Object> rc = (Map<String,Object>)bindingProvider.getRequestContext();
            List<CredentialProvider> credProviders = new ArrayList<CredentialProvider>();
            credProviders.add(new ClientUNTCredentialProvider(
USERNAME .getBytes(),PASSWORD .getBytes()));
            rc.put(WSSecurityContext.CREDENTIAL_PROVIDER_LIST, credProviders);
            rc.put(BindingProvider.USERNAME_PROPERTY, USERNAME);
            rc.put(BindingProvider.PASSWORD_PROPERTY, PASSWORD);;

            dataObjectOperationsByName.insert(input);
        } catch (BAMWebServiceException e) { e.printStackTrace();      }
  }
}