我们正在针对证书验证签名有效负载。有时,我们收到未指定任何“ Id”属性的请求,因此validationContext将不会设置任何Id属性。在这种情况下,我们将收到“ Id不是属性”异常。如果我跳过设置valContext.setIdAttributeNS的操作,那么当几个请求中包含ID时,我们将得到以下异常:
javax.xml.crypto.dsig.XMLSignatureException: javax.xml.crypto.URIReferenceException: com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverException: Cannot resolve element with ID ID-23a2b5ac-1286-4e33-b38f-77350195d92a
是否可以跳过valContext.setIdAttributeNS部分?下面是代码段。
private boolean validateSignature(final Document doc, final PublicKey publicKey) {
LOG.error("In validateSignature");
boolean signatureIsValid = false;
try {
final Node signature = (Node) payLoadSigXPathExpr.evaluate(doc, XPathConstants.NODE);
final Node body = (Node) bodyXPathExpr.evaluate(doc, XPathConstants.NODE);
final Node to = (Node) toXPathExpr.evaluate(doc, XPathConstants.NODE);
final Node messageID = (Node) messageIdXPathExpr.evaluate(doc, XPathConstants.NODE);
final Node replyTo = (Node) replyToXPathExpr.evaluate(doc, XPathConstants.NODE);
final Node action = (Node) actionXPathExpr.evaluate(doc, XPathConstants.NODE);
// Create a DOMValidateContext and specify a KeyValue KeySelector
// and document context
final DOMValidateContext valContext = new DOMValidateContext(KeySelector.singletonKeySelector(publicKey),
signature);
LOG.error("body::"+nodeToString(body));
if(null != body.getAttributes().getNamedItem("Id")){
LOG.error("inside getNamedItem Id");
LOG.error("getNamedItem Id::"+body.getAttributes().getNamedItem("Id").getNodeValue());
valContext.setIdAttributeNS((Element) body,
null, Constants.ID_STRING);
}
if(null != body.getAttributes().getNamedItem("wsu:Id") || null != body.getAttributes().getNamedItem("u:Id")){
LOG.error("inside getNamedItem wsu:Id");
LOG.error("getNamedItem wsu:Id::"+body.getAttributes().getNamedItem("wsu:Id").getNodeValue());
valContext.setIdAttributeNS((Element) body,
Constants.WSSE_SECURITY_UTILITY_NS, Constants.ID_STRING);
}
if (null != messageID) {
LOG.error("messageID::"+nodeToString(messageID));
valContext.setIdAttributeNS((Element) messageID,
Constants.WSSE_SECURITY_UTILITY_NS, Constants.ID_STRING);
}
if (null != replyTo) {
LOG.error("replyTo::"+nodeToString(replyTo));
valContext.setIdAttributeNS((Element) replyTo,
Constants.WSSE_SECURITY_UTILITY_NS, Constants.ID_STRING);
}
if (null != to) {
LOG.error("to::"+nodeToString(to));
valContext.setIdAttributeNS((Element) to,
Constants.WSSE_SECURITY_UTILITY_NS, Constants.ID_STRING);
}
if (null != action) {
LOG.error("action::"+nodeToString(action));
valContext.setIdAttributeNS((Element) action,
Constants.WSSE_SECURITY_UTILITY_NS, Constants.ID_STRING);
}
// Unmarshal the XMLSignature.
final XMLSignature xmlSignature = fac.unmarshalXMLSignature(valContext);
// Validate the XMLSignature.
signatureIsValid = xmlSignature.validate(valContext);
} catch (final Exception ex) {
LOG.error("Signature Validation Exception:{}",ex);
}
return signatureIsValid;
}