How to add security header to SOAP webservice client on java

Posted on 2011-04-18
Last Modified: 2013-11-23
Greetings to all,

I have been developing a Client in netbeans 6.7.1 for a web service using Oasis UsernameToken security, I managed to create the client and the classes from the tool and  the consumer method goes like this

and returns the following Exception:

Error: Security requirements are not satisfied because the security header is not present in the incoming message

I found an example on how to create a Header Handler and I implemented it, but for some reason the function is not called properly and fails to attach the header.

The header has to be something like this:

So my questions are:

Does anybody know a way to successfully append a security header to an outgoing SOAP request?

is there an interface for doing such thing? (in my research i found that a plugin for Glassfish called Access Manager that did all this handling,  but it has been removed for some reason)

What is the proper way to develop a Webservice Client with UsernameToken authentication?

Thanks in advance

<wsse:Security xmlns:wsse=$\"$\">" +
                <wsse:UsernameToken xmlns:wsu=$\"$\">" +
                      <wsse:Username>" + user + "</wsse:Username>" +
                      <wsse:Password Type=$\"$\">password</wsse:Password>" +
                      <wsse:Nonce>" + noncepack + "</wsse:Nonce>" +
                      <wsu:Created>" + sdf.format(c1.getTime()) + "</wsu:Created>" +
              </wsse:UsernameToken>" +

Open in new window

try { // Call Web Service Operation
            xxxxxx.Service service = new xxxxxxx.Service();

            xxxxx.ServiceSoap port = service.getServiceSoap();
            // TODO initialize WS operation arguments here
            java.lang.String subscriberID = "ClientID";
            java.lang.String identity = "Client Identity";
            // TODO process result here
            xxxxxxx.SubscriberRetrieve result = port.retrieveSubscriber(subscriberID, identity);
            info("Result = " + result);
        } catch (Exception ex) {
            error("Error: " + ex);
            // TODO handle custom exceptions here

Open in new window

Question by:Risk_TI
    LVL 23

    Expert Comment

    * This is where you can add your custom SOAP headers if required.
    * Example: WS-Security Username token etc, below shown is a custom
    * Authentication header(not required for this service). just added
    * for example
    SOAPHeader soapHeader = soapMessage.getSOAPHeader();
    Name userName = soapEnvelope.createName("username", "",
    SOAPHeaderElement userNameElement = soapHeader
    Name password = soapEnvelope.createName("password", "",
    SOAPHeaderElement passwordElement = soapHeader
    //Constructing SOAP Body.
    SOAPBody soapBody = soapMessage.getSOAPBody();

    Open in new window

    This is a snippet from my blog, complete article here :

    Author Comment

    thanks shivaspk for your answer, I just want to ask a couple of questions more, that works for a password digest with nonce and timestamp? and once the hearder is create how do I append it to the outgoing SOAP message that JAX-WS sends?

    LVL 23

    Expert Comment

    You can do it as shown here:

    Ya this approach can work for both nonce and timestamp. A nonce is a random value that the sender creates to include in each UsernameToken that it sends. A creation time is added to combine nonces to a "freshness" time period.

    Author Comment

    ok I'm trying to implement the second link you provided me, if successful I give you the points, thank you so much for the response

    Author Comment

    I have come to something like this
    try { // Call Web Service Operation
                com.comverse_in.prepaid.ccws.Service service = 
                new com.comverse_in.prepaid.ccws.Service();
                com.comverse_in.prepaid.ccws.ServiceSoap port = service.getServiceSoap();
    //             TODO initialize WS operation arguments here
                WSBindingProvider bp = (WSBindingProvider) port;
                SOAPMessage message = null;
                message = javax.xml.soap.MessageFactory.newInstance().createMessage();
                SOAPHeader header = message.getSOAPHeader();
                SOAPElement security =
                        header.addChildElement("Security", "wsse", "");
                SOAPElement usernameToken =
                        security.addChildElement("UsernameToken", "wsse");
                usernameToken.addAttribute(new QName("xmlns:wsu"), "");
                SOAPElement username =
                        usernameToken.addChildElement("Username", "wsse");
                SOAPElement password =
                        usernameToken.addChildElement("Password", "wsse");
                password.setAttribute("Type", "");
                //setting up the password Digest
                String unique = UniqId.getInstance().getUniqID();
                BASE64Encoder encoder = new BASE64Encoder();
                String NotEvenOnce = encoder.encode(unique.getBytes());
                //2011-04-05T19:51:46Z Format timestamp 'Y-m-d\TH:i:s\Z'
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
                Calendar c1 = Calendar.getInstance();
                c1.add(Calendar.HOUR_OF_DAY, 6);
                String creaDate = sdf.format(c1.getTime());
                String Hash = hash;
                try {
                     Hash = getHash(NotEvenOnce + creaDate + "C@pt1v0");
                } catch (NoSuchAlgorithmException ex) {
                    error("hash error " + ex);
                // PACKING
                byte[] b = new BigInteger(Hash, 16).toByteArray(); //maybe other
    //        constructor to implement other formats of pack()
                String pack = new String(b, "UTF-8").substring(1); //first char is sign
                String PassDigest = encoder.encode(pack.getBytes());
                SOAPElement nonce =
                        usernameToken.addChildElement("Nonce", "wsse");
    //                        nonce.setAttribute("EncodingType", "");
                SOAPElement created =
                        usernameToken.addChildElement("Created", "wsu");
                //SOAP HEADER Building finished
                java.lang.String subscriberID = "phoneNo";
                java.lang.String identity = "Id";
    //             TODO process result here
                com.comverse_in.prepaid.ccws.SubscriberRetrieveLite result = port.retrieveSubscriberLite(subscriberID, identity);
                info("Result = " + result.getBalance());
                try {
                    handleMessage((SOAPMessageContext) message);
                } catch (Exception e) {
                    info("Excepcion " + e);
            } catch (Exception ex) {
                error("Error calling the WebService: " + ex);

    Open in new window

    Based on the second example given, and that gives me the following error. com.sun.istack.XMLStreamException2: javax.xml.bind.MarshalException - with linked exception: [com.sun.istack.SAXException2: unable to marshal type "com.sun.xml.messaging.saaj.soap.ver1_1.Header1_1Impl" as an element because it is missing an @XmlRootElement annotation]

    What at this time I don't undestand
    LVL 23

    Expert Comment

    What JAX-WS Engine are you using?, Axis2 or Metro? Let me know I will try out a example and provide the actual solution.

    Author Comment

    Thank you Shivaspk, the server I'm using is Apache Tomcat, so I take the guess that is axis the engine. I have been battling with this issue for a while

    very much appreciated.

    Accepted Solution

    well I had come to a solution by myself but thanks for the help

    Author Closing Comment

    because no one else had an answer and I found it by myself

    Expert Comment

    hi, can you please let us know how did you implement this. I have similar requirement, your solution can help me.

    Featured Post

    How to run any project with ease

    Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
    - Combine task lists, docs, spreadsheets, and chat in one
    - View and edit from mobile/offline
    - Cut down on emails

    Join & Write a Comment

    Suggested Solutions

    Title # Comments Views Activity
    Tool to email me when a website changes 29 92
    hasOne  challenge 59 66
    dividesSelf challange 15 61
    bunnyEars challenge 6 47
    The task of choosing a web design company to build a website for your business should never be taken in a light manner. Provided the fact that your website will act as a representative to your business and will be responsible for imposing an online …
    Introduction Knockoutjs (Knockout) is a JavaScript framework (Model View ViewModel or MVVM framework).   The main ideology behind Knockout is to control from JavaScript how a page looks whilst creating an engaging user experience in the least …
    The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
    HTML5 has deprecated a few of the older ways of showing media as well as offering up a new way to create games and animations. Audio, video, and canvas are just a few of the adjustments made between XHTML and HTML5. As we learned in our last micr…

    746 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    19 Experts available now in Live!

    Get 1:1 Help Now