use of org.apache.wss4j.common.util.WSTimeSource in project iaf by ibissource.
the class SoapWrapper method signMessage.
public Message signMessage(Message soapMessage, String user, String password, boolean passwordDigest) {
try {
// We only support signing for soap1_1 ?
// Create an empty message and populate it later. createMessage(MimeHeaders, InputStream) requires proper headers to be set which we do not have...
MessageFactory factory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL);
SOAPMessage msg = factory.createMessage();
SOAPPart part = msg.getSOAPPart();
part.setContent(new StreamSource(soapMessage.asInputStream()));
// create unsigned envelope
SOAPEnvelope unsignedEnvelope = part.getEnvelope();
Document doc = unsignedEnvelope.getOwnerDocument();
// create security header and insert it into unsigned envelope
WSSecHeader secHeader = new WSSecHeader(doc);
secHeader.insertSecurityHeader();
// add a UsernameToken
WSSecUsernameToken tokenBuilder = new WSSecUsernameToken(secHeader);
tokenBuilder.setIdAllocator(idAllocator);
if (passwordDigest) {
tokenBuilder.setPasswordType(WSConstants.PASSWORD_DIGEST);
} else {
tokenBuilder.setPasswordType(WSConstants.PASSWORD_TEXT);
}
tokenBuilder.setPrecisionInMilliSeconds(false);
tokenBuilder.setUserInfo(user, password);
WSTimeSource timesource = tokenBuilder.getWsTimeSource();
tokenBuilder.addNonce();
tokenBuilder.addCreated();
tokenBuilder.prepare(null);
Element element = tokenBuilder.getUsernameTokenElement();
String nonce = XmlUtils.getChildTagAsString(element, "wsse:Nonce");
byte[] decodedNonce = org.apache.xml.security.utils.XMLUtils.decode(nonce);
String created = XmlUtils.getChildTagAsString(element, "wsu:Created");
WSSecSignature sign = new WSSecSignature(secHeader);
sign.setIdAllocator(idAllocator);
sign.setCustomTokenValueType(WSConstants.WSS_USERNAME_TOKEN_VALUE_TYPE);
sign.setCustomTokenId(tokenBuilder.getId());
sign.setSigCanonicalization(WSConstants.C14N_EXCL_OMIT_COMMENTS);
sign.setAddInclusivePrefixes(false);
// conform WS-Trust spec
String signatureValue = UsernameTokenUtil.doPasswordDigest(decodedNonce, created, password);
sign.setSecretKey(signatureValue.getBytes(StreamUtil.DEFAULT_CHARSET));
// UT_SIGNING no longer exists since v1.5.11
sign.setKeyIdentifierType(WSConstants.CUSTOM_SYMM_SIGNING);
sign.setSignatureAlgorithm(WSConstants.HMAC_SHA1);
sign.build(null);
tokenBuilder.prependToHeader();
// add a Timestamp
WSSecTimestamp timestampBuilder = new WSSecTimestamp(secHeader);
timestampBuilder.setWsTimeSource(timesource);
timestampBuilder.setTimeToLive(300);
timestampBuilder.setIdAllocator(idAllocator);
timestampBuilder.build();
return new Message(doc);
} catch (Exception e) {
throw new RuntimeException("Could not sign message", e);
}
}
Aggregations