CXF SOAP Client Example to Use Plain Text Password Authentication

CXF SOAP client can be configured to support various web authentication strategies via its out WSS4JOutInterceptor. For example it can be configured to support plain text username/password or digest based authentication. This post will show the plain text case. 

First of all, you need to add cxf-rt-ws-security and cxf-rt-frontend-jaxws to your dependencies.

With that you can use the following code to to access a  secured endpoint (which is MyService in this example).


//Example code

createSecureService(MyService.class, "https://example.com/soap/example",1000, 2000, "user", "password");

private <S> S createSecureService(Class<S> serviceClass, String url, long connectionTimeout,
  long receiveTimeout, String username, String password) {
  JaxWsProxyFactoryBean jaxWsFactory = new JaxWsProxyFactoryBean();
  jaxWsFactory.setServiceClass(serviceClass);
  jaxWsFactory.setAddress(url);
  @SuppressWarnings("unchecked")
  S service = (S) jaxWsFactory.create();
  Client client = ClientProxy.getClient(service);
  Endpoint cxfEndpoint = client.getEndpoint();
  Map<String, Object> outProps = new HashMap<String, Object>();
  outProps.put(WSHandlerConstants.ACTION, WSHandlerConstants.USERNAME_TOKEN);
  outProps.put(WSHandlerConstants.USER, username);
  outProps.put(WSHandlerConstants.PASSWORD_TYPE, WSConstants.PW_TEXT);
  outProps.put(WSHandlerConstants.PW_CALLBACK_REF, new CallbackHandler() {
    @Override
    public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
      Arrays.stream(callbacks).filter(WSPasswordCallback.class::isInstance)
      .map(WSPasswordCallback.class::cast)
      .forEach(callback -> callback.setPassword(password));
    }
  });
  WSS4JOutInterceptor wssOut = new WSS4JOutInterceptor(outProps);
  cxfEndpoint.getOutInterceptors().add(wssOut);
  configureClient(connectionTimeout, receiveTimeout, client);
  return service;
}

private void configureClient(long connectionTimeout, long receiveTimeout, Client client) {
  HTTPConduit http = (HTTPConduit) client.getConduit();
  HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
  httpClientPolicy.setConnectionTimeout(connectionTimeout);
  httpClientPolicy.setReceiveTimeout(receiveTimeout);
  http.setClient(httpClientPolicy);
}

Advertisements
This entry was posted in Java and tagged , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s