Apache CXF UsernameToken authentication with Nonce

Dec 20, 2010   #java  #webservices 

Glen describes how to use the UsernameToken profile with Apache CXF.

I had the additional requirement of putting a message nonce and a “created” timestamp into the SOAP header to prevent message replay attacks.

Adding these two tags and their content requires only one additional line of code compared to Glen’s example. This is how you do it:

...
HashMap outProps = new HashMap();
Client client = org.apache.cxf.frontend.ClientProxy.getClient(portInterface);
Endpoint cxfEndpoint = client.getEndpoint();

outProps.put(WSHandlerConstants.ACTION, WSHandlerConstants.USERNAME_TOKEN);
outProps.put(WSHandlerConstants.USER, "Username");
outProps.put(WSHandlerConstants.PASSWORD_TYPE, WSConstants.PW_TEXT);
// Automatically adds a Base64 encoded message nonce and a created timestamp
outProps.put(WSHandlerConstants.ADD_UT_ELEMENTS, WSConstants.NONCE_LN + " " + WSConstants.CREATED_LN); 
// You must implement the PasswordCallback class yourself. See Glen's page mentioned above for how 
outProps.put(WSHandlerConstants.PW_CALLBACK_CLASS, PasswordCallback.class.getName()); to do it

WSS4JOutInterceptor wssOut = new WSS4JOutInterceptor(outProps);
cxfEndpoint.getOutInterceptors().add(wssOut);

And this is what you get:

<soap:Header>
    <wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
    soap:mustUnderstand="1">
      <wsse:UsernameToken xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
      xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
      wsu:Id="UsernameToken-1">
        <wsse:Username>Username</wsse:Username>
        <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">
        myPassword1234</wsse:Password>
        <wsse:Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">
        6hn0vYMlV7OoBy+TjmKMrw==</wsse:Nonce>
        <wsu:Created>2010-12-20T11:53:41.790Z</wsu:Created>
      </wsse:UsernameToken>
    </wsse:Security>
  </soap:Header>