protected void addToken(SoapMessage message) {
    UsernameToken tok = assertTokens(message);

    Header h = findSecurityHeader(message, true);
    WSSecUsernameToken utBuilder = addUsernameToken(message, tok);
    if (utBuilder == null) {
      AssertionInfoMap aim = message.get(AssertionInfoMap.class);
      Collection<AssertionInfo> ais = getAllAssertionsByLocalname(aim, SPConstants.USERNAME_TOKEN);
      for (AssertionInfo ai : ais) {
        if (ai.isAsserted()) {
          ai.setAsserted(false);
        }
      }
      return;
    }
    Element el = (Element) h.getObject();
    utBuilder.prepare(el.getOwnerDocument());
    el.appendChild(utBuilder.getUsernameTokenElement());
  }
  protected WSSecUsernameToken addUsernameToken(SoapMessage message, UsernameToken token) {
    String userName = (String) message.getContextualProperty(SecurityConstants.USERNAME);
    WSSConfig wssConfig = (WSSConfig) message.getContextualProperty(WSSConfig.class.getName());
    if (wssConfig == null) {
      wssConfig = WSSConfig.getNewInstance();
    }

    if (!StringUtils.isEmpty(userName)) {
      // If NoPassword property is set we don't need to set the password
      if (token.getPasswordType() == UsernameToken.PasswordType.NoPassword) {
        WSSecUsernameToken utBuilder = new WSSecUsernameToken(wssConfig);
        utBuilder.setUserInfo(userName, null);
        utBuilder.setPasswordType(null);
        return utBuilder;
      }

      String password = (String) message.getContextualProperty(SecurityConstants.PASSWORD);
      if (StringUtils.isEmpty(password)) {
        password = getPassword(userName, token, WSPasswordCallback.USERNAME_TOKEN, message);
      }

      if (!StringUtils.isEmpty(password)) {
        // If the password is available then build the token
        WSSecUsernameToken utBuilder = new WSSecUsernameToken(wssConfig);
        if (token.getPasswordType() == UsernameToken.PasswordType.HashPassword) {
          utBuilder.setPasswordType(WSConstants.PASSWORD_DIGEST);
        } else {
          utBuilder.setPasswordType(WSConstants.PASSWORD_TEXT);
        }

        utBuilder.setUserInfo(userName, password);
        return utBuilder;
      } else {
        policyNotAsserted(token, "No username available", message);
      }
    } else {
      policyNotAsserted(token, "No username available", message);
    }
    return null;
  }