javaxmlsoapws-securityusernametoken

UserNameToken in soap from Java


I am trying to use a gSoap-generated wsdl from Netbeans. The webservice requires that the UserNameToken be passed in. When I use the wsdl from SoapUI (which works), it sends this:

<wsse:Username>myname</wsse:Username>
<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">mypass</wsse:Password>

However, when I try it from Netbeans using a handler (referred to by How do I add a SOAP Header using Java JAX-WS) like this:

            String prefix = "wsse";
            String uri = "http://...wsssecurity...";

            SOAPElement securityElem = factory.createElement("Security",prefix,uri);

                SOAPElement UserNametokenElem = factory.createElement("UserNameToken",prefix,uri);

                    SOAPElement UsernameElem = factory.createElement("wsse:Username");
                    UsernameElem.addTextNode("myname");
                    SOAPElement PasswordElem = factory.createElement("Password");
                    PasswordElem.addTextNode("mypass");

                    UserNametokenElem.addChildElement(UsernameElem);
                    UserNametokenElem.addChildElement(PasswordElem);

                    securityElem.addChildElement(UserNametokenElem);
            SOAPHeader header = envelope.addHeader();
            header.addChildElement(securityElem);

it generates the soap headers like this:

    <wsse:Security xmlns:wsse="http://...wsssecurity...">
    <wsse:UserNameToken xmlns:wsse="http://...wsssecurity...">
    <Username xmlns="">myname</Username>
    <Password xmlns="">mypass</Password>
    </wsse:UserNameToken>
    </wsse:Security>

which causes the webservice to reply with an authentication error.

My questions are therefore:

  1. How do I generate the UserNameToken in the correct way (as SoapUi does)?
  2. Is it better to do it using a handler, or an external WSSE library like Apache WSS4J (can someone show me some sample code for this)

Solution

  • I eventually successfully used wss4j, and did something like this:

                SOAPPart soappart = message.getSOAPPart();
                SOAPEnvelope envelope = soappart.getEnvelope();
                SOAPHeader header = envelope.getHeader();
                WSSecHeader wsheader = new WSSecHeader();
                wsheader.insertSecurityHeader(soappart);
                WSSecUsernameToken token = new WSSecUsernameToken();
                token.setPasswordType(WSConstants.PASSWORD_DIGEST);
                token.setUserInfo("myuser", "mypass");
                token.build(soappart, wsheader);
    

    wss4j had some nested dependencies, so watch out for that.