Sunday, May 22, 2011

Enabling WS-Security Username Token Profile for Apache CXF service

This article describes how to create a code first webservice. I am going to extend the sample provided to support WS-Security Username Token profile. It is a way for the callers of the service to prove their identity by providing username and a password.

To recap the previous article, it is very simple to expose a code first webservice using Apache CXF with Spring. Apache CXF provides a custom Spring namespace to easily configure the endpoint:

<beans xmlns=""
 xmlns:xsi="" xmlns:aop=""


 <bean id="memberendpoint" class="org.bk.memberservice.endpoint.DefaultMemberEndpoint"/>
 <jaxws:endpoint address="/memberservice" id="memberservicehttp" implementor="#memberendpoint" >


This exposes the memberendpoint bean above as a fully configured webservice.

To secure this service using usernametoken, first implement a callback for CXF to invoke to validate the credentials passed by the user:

package org.bk.memberservice.endpoint;




public class UsernameTokenCallback implements CallbackHandler {

 public void handle(Callback[] callbacks) throws IOException,
   UnsupportedCallbackException {
  Callback callback = callbacks[0];
  WSPasswordCallback pc = (WSPasswordCallback) callback;
//              Retrieve and set the real password..which will be validated 
//              by CXF validator against the digest password
  System.out.println("Received cred: " + pc.getIdentifier() + " : " + pc.getPassword());
//  validate the credentials
//              boolean isValid = true;
//              throw IO Exception if the credentials are not valid
//  if (!isValid) {
//   throw new IOException("Bad Credentials");
//  }

To wire this Callback handler with the service endpoint, CXF uses a concept called the interceptor, basically the webservice call is handled by the interceptors before being handed over to the service.

   <bean class="">
      <entry key="passwordCallbackRef">
       <ref bean="usernameTokenCallback" />

That's it!! the endpoint is now secured using UsernameToken profile. To test this, bring up the endpoint, use SOAP UI to send a normal request, it will fail with the message that a ws-security header is required - this is the username token soap header that is expected as part of the request.

 Fix this by adding the username and password, select "digest" as the password type and the service invocation should just work.
Updated Sample available at: git://
1. WS-Security reference in Wikipedia:
2. WS-Secuirty usernametoken profile specs at OASIS:
3. Apache CXF reference:
4. New changes as part of WSS4J -


  1. However, the WSDL doesn't contain the security policy. This make it difficult for client to know that WS-Security is to be used.

  2. nicely & cleanly explained