Mike Thomsen
Mike Thomsen

Reputation: 37506

Adding ws-security to wsdl2java generated classes

I generated a bunch of client classes from a WSDL with CXF's wsdl2java. How do I add WS-Security to the header when doing something like this:

URL url = new URL("http://fqdn:8080/service/MessageHandler");
MessageHandlerService service = new MessageHandlerService(url);
MessageHandler handler = service.getMessageHandler();
MyMessage message = new MyMessage();
message.setSender("User 1");
handler.sendMessage(message);

I think handler is a javax.xml.ws.Service instance.

Upvotes: 4

Views: 15042

Answers (2)

Mike Thomsen
Mike Thomsen

Reputation: 37506

<jaxws:client id="client"
    serviceClass="com.mycompany.TheServiceInterface"
    address="http://fqdn/service/Endpoint?wsdl">
    <jaxws:outInterceptors>
        <bean class="org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor">
            <constructor-arg>
                <map>
                    <entry key="action" value="Timestamp UsernameToken"/>
                    <entry key="user" value="test.user"/>
                    <entry key="passwordType" value="PasswordNone"/>
                </map>
            </constructor-arg>
        </bean>
    </jaxws:outInterceptors>
</jaxws:client>

Then if you cast the client to a BindingProvider you can change the endpoint as needed programatically.

Upvotes: 0

TheWhiteRabbit
TheWhiteRabbit

Reputation: 15758

Usually it's done outside the code .

In that case THIS might help

If you want to add programatically ,

Programmatically adding the WS-Security UsernameToken header to the Axis binding, non-standard, but useful for quick tests. (Stub/Binding: it's the class that ends with _PortType)

/**
  * Adds WS-Security header with UsernameToken element to the Axis binding
  * @param binding
  * @param wsUser
  * @param wsPass
  * @throws SOAPException
  */
 protected static void addWsSecurityHeader(org.apache.axis.client.Stub binding, String wsUser, String wsPass)
   throws SOAPException {

  // Create the top-level WS-Security SOAP header XML name.
  QName headerName = new QName(
    "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "Security");
  SOAPHeaderElement header = new SOAPHeaderElement(headerName);
  //  no intermediate actors are involved.
  header.setActor(null);
  // not important, "wsse" is standard
  header.setPrefix("wsse");
  header.setMustUnderstand(true);

  // Add the UsernameToken element to the WS-Security header
  SOAPElement utElem = header.addChildElement("UsernameToken");
  SOAPElement userNameElem = utElem.addChildElement("Username");
  userNameElem.setValue(wsUser);
  SOAPElement passwordElem = utElem.addChildElement("Password");
  passwordElem.setValue(wsPass);

  // Finally, attach the header to the binding.
  binding.setHeader(header);
 }

Upvotes: 8

Related Questions