3/17/15

HTTP basic authentication with JAX-WS (Client)

HTTP basic authentication with JAX-WS (Client)

JAX-WS does not do very well with HTTP basic authentication. In general, to create and use a web-service client you have to perform the following steps: 1. Use wsimport to generate the stub files 2. Create a service class in the client 3. Retrieve a proxy to the service, also known as a port All three steps could require HTTP basic authentication. And for each step it have to be handled in a different way.

1. The stub files generation

If access to a wsdl file is restricted with basic authentication, wsimport fails to get it. Unfortunately it does not support the common approach to write access credentials right into the 
URL (RFC 1738). It is not a big deal to resolve this issue. You just need to create a server authentication file: $HOME/.metro/auth. This file should have the WSDL URL with username and password in the RFC 1738 format:
http[s]://user:password@host:port//
You can have line delimited multiple entries in this file and they can be used for various sites that need basic authentication.

2. The service class creation

A constructor of the service object requires access to the WSDL. And again it does not support basic authentication out of the box. You have an option to download the wsdl file and use it locally. Another option is to use the default authenticator:
Authenticator.setDefault(new Authenticator() {
 @Override
 protected PasswordAuthentication getPasswordAuthentication() {
   return new PasswordAuthentication(
     USER_NAME,
     PASSWORD.toCharArray());
 }
});

3. The service class configuration

And the last but not least part of our adventure is configuration of the service port:
OurWebService service = new OurWebService ();
OurWebServicePortType port = service.getOurWebServicePortType();

BindingProvider bindingProvider = (BindingProvider)port;
Map requestContext = bindingProvider.getRequestContext();
requestContext.put(BindingProvider.USERNAME_PROPERTY, USER_NAME);
requestContext.put(BindingProvider.PASSWORD_PROPERTY, PASSWORD);

4. using client http:
        Client client = ClientProxy.getClient(port);
        HTTPConduit http = (HTTPConduit) client.getConduit();
        http.getAuthorization().setUserName("vn_IVR_User");
        http.getAuthorization().setPassword("FinopbigNac4");


Done!
 Now you are able to use methods of the port object to communicate with a web service.

No comments: