Implementing WS-Security with JSR 181 Annotations using WSS4J in XFire

The Logemann Blog really helped me out when I was trying to use JSR181 Annotations in favor of the services.xml configuration in XFire. Reading that blog entry is most likely a prerequisite for this one. Once you’ve configured your Spring beans and web.xml to use JSR181 Annotations, the next step is to implement security for your web services. The example shown implements WS-Security as specified by OASIS Web Services Security and implemented by WSS4J in XFire.

Looking at the ws-security example packaged with XFire, for a service to be security enabled, you need the following configuration in your services.xml. We are dealing with the “User Token with Hashed Password” scheme.

  <handler handlerClass=
    "org.codehaus.xfire.util.dom.DOMInHandler" />
  <bean class=
   <property name="properties">
     <prop key="action">UsernameToken</prop>
     <prop key="passwordCallbackClass">
  <handler handlerClass=

However, we want to substitute this configuration with annotations. There are three InHandlers being applied which we must specify via annotations. The problem is that when specifying handlers using annotations you may not supply any parameters to them, as we do above in the case of WSS4JInHandler. The solution is to create a custom handler which wraps the other handlers and passes in the parameters to WSS4JInHandler programmatically. Here’s a custom handler which does just that:

public class WSSecurityHandler
                  extends AbstractHandler {
 List<Handler> inHandlers;

 public WSSecurityHandler() {
  WSS4JInHandler wss4jInHandler;
  ValidateUserTokenHandler userTokenHandler;
  Properties props = new Properties();
  props.put("action", "UsernameToken");

  wss4jInHandler = new WSS4JInHandler(props);
  userTokenHandler = new ValidateUserTokenHandler();
  inHandlers = new ArrayList<Handler>();

public QName[] getUnderstoodHeaders() {
  return new QName[] {
    new QName("" +
 public void invoke(MessageContext messageContext)
                                   throws Exception {
  for (Handler handler : inHandlers) {
  // User should be set by ValidateUserTokenHandler
  // You can also choose to do all your security checks in
  // ValidateUserTokenHandler which does a lot of the work for you
  if (messageContext.getProperty(
        WSHandlerConstants.ENCRYPTION_USER) == null) {
    throw new Exception("Principal not found");


The implementation is fairly straightforward. The one thing to note is the getUnderstoodHeaders() method which returns a QName. The reason this is important is that Java clients send this as part of the SOAP header and it is mandatory for the web service to recognize this as a valid header. I encountered this problem and reported it on the mailing list with no response.

The last piece of the puzzle is that we must annotate our web service class with our custom handler. Here’s an example:

public class BookService {
 // methods go here

The DOMInHandler must be configured via an annotation. The client code for calling a web service configured using services.xml is the same as when configured via annotations:

Service serviceModel = new ObjectServiceFactory().
IBook service = (IBook) new XFireProxyFactory().
create(serviceModel, SERVICE_URL);

Client client = ((XFireProxy)
client.addOutHandler(new DOMOutHandler());
Properties p = new Properties();
// Action to perform : user token
// Set password type to hashed
// Username in keystore
p.setProperty(WSHandlerConstants.USER, "serveralias");
// Used do retrive password for given user name

client.addOutHandler(new WSS4JOutHandler(p));
Book b = service.findBook("0123456789");

That’s all it takes.


30 thoughts on “Implementing WS-Security with JSR 181 Annotations using WSS4J in XFire

  1. deno

    great article!

    what binding style are you using? are you doing code or schema first development? are you using org.codehaus.xfire.spring.remoting.Jsr181HandlerMapping or org.codehaus.xfire.spring.ServiceBean to expose your services?

    BTW – some of your code is cut off on the right side.

  2. arsenalist

    I am following what the Logemann Blog is doing so yes I’m using Jsr181HandlerMapping. I didn’t want to reproduce that blog entry here. You should refer to it.

    I am utilizing the stubs generated by the XFire’s WsGen command based on the WSDL.

  3. deno

    When I add the WSS4JOutHandler to the client I’m getting a NamespaceURI cannot be null expection. What Namespace is the expection referring to?

  4. deno

    i am following the XFire distro example.

    Service serviceModel = new ObjectServiceFactory().create(VehicleLookupService.class,”VehicleLookupService”, SERVICE_NAMESPACE, null);
    VehicleLookupService service = (VehicleLookupService) new XFireProxyFactory().create(serviceModel,_serviceUrl);

    Client client = ((XFireProxy) Proxy.getInvocationHandler(service)).getClient();
    client.addOutHandler(new DOMOutHandler());
    Properties properties = new Properties();
    //client.addOutHandler(new WSS4JOutHandler(properties)); // this is the line that breaks

    LookupVehiclesRequest lookupRequest = RequestBuilder.buildLookupVehiclesRequest(cmd);
    LookupVehiclesResponse r = service.getVehicles(lookupRequest);

    protected void configureOutProperties(Properties properties) {
    properties.setProperty(WSHandlerConstants.ACTION, WSHandlerConstants.USERNAME_TOKEN);
    properties.setProperty(WSHandlerConstants.PASSWORD_TYPE, WSConstants.PW_DIGEST);
    properties.setProperty(WSHandlerConstants.USER, “root”);
    properties.setProperty(WSHandlerConstants.PW_CALLBACK_CLASS, PasswordHandler.class.getName());

  5. deno

    ?xml version=”1.0″ encoding=”UTF-8″?>
    wsdl:definitions targetNamespace=”” xmlns:tns=”” xmlns:wsdlsoap=”” xmlns:soap12=”” xmlns:ns1=”” xmlns:xsd=”” xmlns:soapenc11=”” xmlns:soapenc12=”” xmlns:soap11=”” xmlns:wsdl=””>

  6. deno

    it’s this line

    client.addOutHandler(new WSS4JOutHandler(properties));

    that throws the expection. the server side seems to be all good as i can all consume my service with a php client along with a xfire client (as long as i don’t add the WSS4JOutHandler to the client.

  7. deno

    yeah, it does seem like a weird problem. here’s the stack trace

    2007-02-04 12:45:21,947 ERROR [org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/oracle].[spring]] – Servlet.service() for servlet spring threw exception
    org.codehaus.xfire.XFireRuntimeException: Could not invoke service.. Nested exception is org.codehaus.xfire.fault.XFireFault: NamespaceURI cannot be null
    org.codehaus.xfire.fault.XFireFault: NamespaceURI cannot be null
    at org.codehaus.xfire.fault.XFireFault.createFault(
    at org.codehaus.xfire.util.dom.DOMSerializer.writeMessage(
    at org.codehaus.xfire.transport.http.HttpChannel.writeWithoutAttachments(
    at org.codehaus.xfire.transport.http.CommonsHttpMessageSender.getByteArrayRequestEntity(
    at org.codehaus.xfire.transport.http.CommonsHttpMessageSender.send(
    at org.codehaus.xfire.transport.http.HttpChannel.sendViaClient(
    at org.codehaus.xfire.transport.http.HttpChannel.send(
    at org.codehaus.xfire.handler.OutMessageSender.invoke(
    at org.codehaus.xfire.handler.HandlerPipeline.invoke(
    at org.codehaus.xfire.client.Invocation.invoke(
    at org.codehaus.xfire.client.Client.invoke(
    at org.codehaus.xfire.client.XFireProxy.handleRequest(
    at org.codehaus.xfire.client.XFireProxy.invoke(
    at $Proxy19.getVehicles(Unknown Source)
    at com.autoreturn.service.VehicleLookupServiceController.handle(
    at org.springframework.web.servlet.mvc.AbstractCommandController.handleRequestInternal(
    at org.springframework.web.servlet.mvc.AbstractController.handleRequest(
    at org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(
    at org.springframework.web.servlet.DispatcherServlet.doService(
    at org.springframework.web.servlet.FrameworkServlet.processRequest(
    at org.springframework.web.servlet.FrameworkServlet.doGet(
    at javax.servlet.http.HttpServlet.service(
    at javax.servlet.http.HttpServlet.service(
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(
    at org.apache.catalina.core.StandardWrapperValve.invoke(
    at org.apache.catalina.core.StandardContextValve.invoke(
    at org.apache.catalina.core.StandardHostValve.invoke(
    at org.apache.catalina.valves.ErrorReportValve.invoke(
    at org.apache.catalina.core.StandardEngineValve.invoke(
    at org.apache.catalina.connector.CoyoteAdapter.service(
    at org.apache.coyote.http11.Http11Processor.process(
    at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(
    at org.apache.tomcat.util.threads.ThreadPool$
    Caused by: NamespaceURI cannot be null
    at org.codehaus.xfire.util.STAXUtils.writeElement(
    at org.codehaus.xfire.util.STAXUtils.writeNode(
    at org.codehaus.xfire.util.STAXUtils.writeElement(
    at org.codehaus.xfire.util.STAXUtils.writeNode(
    at org.codehaus.xfire.util.STAXUtils.writeElement(
    at org.codehaus.xfire.util.STAXUtils.writeNode(
    at org.codehaus.xfire.util.STAXUtils.writeElement(
    at org.codehaus.xfire.util.STAXUtils.writeNode(
    at org.codehaus.xfire.util.STAXUtils.writeElement(
    at org.codehaus.xfire.util.STAXUtils.writeDocument(
    at org.codehaus.xfire.util.dom.DOMSerializer.writeMessage(
    … 36 more

  8. Pingback: Writing PHP clients for XFire, Axis and .NET Web Services « The Arsenalist Muses

  9. Marc


    I am having a problem compiling since @InHandler annotation import is missing. What do I use for the import?

  10. michael

    Hi, I’ve got problem in finding classes: ValidateUserTokenHandler and PasswordHandler ; what should I import/install to get them?

  11. michael

    Thx, got it 🙂 Now I have problems with adding other kinds of WS-Security elements, i.e. timestamp. Just adding another in/out handler doesn’t work :/ (action mismatch…) Where can I get more feedback on it?

  12. Alex

    hi.. i’m getting the same problem deno got…
    can you please tell me what solution he found??

    thanks a lot!

  13. arsenalist

    He was using JARs from different places. Some from XFire, some for JAXB, etc etc. Make sure ALL the jars you use in your client are from the XFire distribution.

  14. Andoko

    Hi, i experienced exactly the same problem with deno, when i add wss4jouthandler, it turned out that my client gave xfire exception that says namespace uri cannot be null. i ve been looking for workaround for this problem with no avail, thanks very much, hope someone can help . . .

  15. Andoko

    Thanks for your fast response could you mail me your working client please? i use library other than xfire just for WSConstants, WSHandlerConstants, and WSS4JHandler from package, my other import is from xfire package. here is my import list :

    import java.util.Properties;
    import org.codehaus.xfire.client.Client;
    import org.codehaus.xfire.service.binding.ObjectServiceFactory;
    import org.codehaus.xfire.util.dom.DOMOutHandler;
    import org.codehaus.xfire.service.Service;
    import org.codehaus.xfire.client.XFireProxyFactory;
    import org.codehaus.xfire.service.ServiceFactory;
    //non – ws import
    import os3.bussiness.beans.*;
    import java.util.List;

    are those package correct? i use wss4j-1.5.2.jar, xfire-all-1.2.6.jar.

    thanks in advance

  16. Lou

    Would there be any reason I couldn’t use this same approach if I’m using spring rather than services.xml?


  17. hugh

    re: NamespaceURI cannot be null

    This stumped me for a while, then I added a DebugHandler that does this:

    OutMessage msg = (OutMessage) messageContext.getCurrentMessage();
    Document doc = (Document) msg.getProperty("dom.message");

    XMLSerializer ser = new XMLSerializer();
    ser.setOutputFormat(new OutputFormat("xml", null, true));
    ser.setOutputCharStream(new PrintWriter(System.out));

    Which revealed that the WSS4JOutHandler was not putting the correct NS prefix on the Password Type attribute.

    I got around this by then adding a PatchWSS4JOutHandler which did the following on invocation:

    OutMessage msg = (OutMessage) messageContext.getCurrentMessage();
    Document doc = (Document) msg.getProperty("dom.message");

    Node typeNode = XPathAPI.selectSingleNode(doc, "//@Type");
    Attr typeAttr = (Attr) typeNode;
    Element passwordElement = typeAttr.getOwnerElement();
    Attr replacement = doc.createAttributeNS("", "Type");

    Which is ugly but it works.

  18. Henrik

    Hi. I’m getting the same exception as Deno above.
    When I implemented the solution which “hugh” presented above everything works nicely (thanks).
    However, when I try to encrypt my WebServices as described in the xfire-1.2.6 distribution I still get “NamespaceURI can not be null”.

    I have replaced


    replacement.setPrefix(“wsse”); with replacement.setPrefix(“xenc”);

    but still no success.

    Has anyone seen this before?

  19. Martina

    Hey! Do you know if they make any plugins to protect against hackers?
    I’m kinda paranoid about losing everything I’ve worked hard on.

    Any suggestions?


Leave a Reply

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

You are commenting using your 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 )

Connecting to %s