WSS4J WSSecUsernameToken problem

I'm having trouble adding a Username Token header to an existing SOAP message. My code looks like this:

            MessageFactory mf = MessageFactory.newInstance();
            SOAPMessage sm = mf.createMessage();
            SOAPPart soappart = sm.getSOAPPart();
            SOAPEnvelope se = soappart.getEnvelope();
            SOAPHeader header = se.getHeader();
            String username = "wss4j";
            String password = "security";        
            WSSecHeader wsheader = new WSSecHeader();
            WSSecUsernameToken  token = new WSSecUsernameToken();
            token.setUserInfo(username, password);
  , wsheader);

What it produces is this:

<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="" xmlns:xsd="" xmlns:xsi="">
    <wsse:Security xmlns:wsse="" soapenv:mustUnderstand="0"/>
    <soapenv:client-session-id soapenv:actor="" soapenv:mustUnderstand="0">876351D116F8A209E609BAA99683CF71</soapenv:client-session-id>

As you can see, the wsse:Security element does not contain the Username Token as it should. What I'm trying to produce is something like this:

<wsse:Security xmlns:wsse="" soapenv:actor="test" soapenv:mustUnderstand="1">
  <wsse:UsernameToken xmlns:wsu="" wsu:Id="UsernameToken-32699917">
    <wsse:Password Type="">this is a lot of foobar </wsse:Password>

A co-worker ran the code and it produced the right SOAP. But when I run it, the Username Token isn't there.
Who is Participating?
Siva Prasanna KumarPrincipal Solutions ArchitectCommented:
Are you using the article  link

check the sample code or Listing 2 thats what you are suppose to do.

Any way just try this

Replace the following lines
WSSecUsernameToken  token = new WSSecUsernameToken();
            token.setUserInfo(username, password);
  , wsheader);


WSSAddUsernameToken token=  new WSSAddUsernameToken("", false);
//as your example shows password is text.
token.setPasswordType(WSConstants.PASSWORD_TEXT);, username, password);

Actually i don't see any major mistake in your code. any way try the above code and let me know whats the result.

FeralCTOAuthor Commented:
I get the same result. It's odd. I can step through code, into the wss4j source, and see that the Username Token gets created and looks the way it should. I can even see it get added to the security header. But once I come out of that code and back into mine, the security header doesn't contain the Username Token.
FeralCTOAuthor Commented:
I got this working by moving the Username Token code further down to just before the method is invoked. I don't know why that made a difference, but it did.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.