Soap request signing - soap

Hello fellow developers,
I have no experience working on soap, saml and xml signing,
I am trying to generate this structure and then add 2 signature tags to it.
<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope">
<env:Header xmlns:a="http://www.w3.org/2005/08/addressing">
<a:MessageID></a:MessageID>
<a:To env:mustUnderstand="true"></a:To>
<a:Action env:mustUnderstand="true">urn:hl7-org:v3:PRPA_IN201305UV02:CrossGatewayPatientDiscovery</a:Action>
<wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
<wsu:Timestamp wsu:Id="timestamp_ID">
<wsu:Created>2022-10-13T18:18:17.763Z</wsu:Created>
<wsu:Expires>2023-10-13T18:23:17.763Z</wsu:Expires>
</wsu:Timestamp>
<saml2:Assertion xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ID="assertion_ID" IssueInstant="2022-10-13T18:18:17.763Z" Version="2.0">
<saml2:Issuer Format="urn:oasis:names:tc:SAML:2.0:nameid-format:X509SubjectName"></saml2:Issuer>
<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
<SignedInfo>
<CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
<SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
<Reference URI="#assertion_ID">
<Transforms>
<Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
<Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
</Transforms>
<DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
<DigestValue></DigestValue>
</Reference>
</SignedInfo>
<SignatureValue></SignatureValue>
<KeyInfo>
<X509Data>
<X509Certificate></X509Certificate>
</X509Data>
</KeyInfo>
</Signature>
<saml2:Subject>
<saml2:NameID Format="urn:oasis:names:tc:SAML:1.1:nameid-format:X509SubjectName"></saml2:NameID>
<saml2:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:holder-of-key">
<saml2:SubjectConfirmationData>
<KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
<KeyValue>
<RSAKeyValue>
<Modulus></Modulus>
<Exponent>AQAB</Exponent>
</RSAKeyValue>
</KeyValue>
</KeyInfo>
</saml2:SubjectConfirmationData>
</saml2:SubjectConfirmation>
</saml2:Subject>
<saml2:Conditions NotBefore="2022-10-13T18:15:17.763Z" NotOnOrAfter="2022-10-13T18:23:17.763Z">
<saml2:AudienceRestriction>
<saml2:Audience></saml2:Audience>
</saml2:AudienceRestriction>
</saml2:Conditions>
<saml2:AuthnStatement AuthnInstant="2022-10-13T17:55:17.743Z" SessionIndex="1234567890">
<saml2:SubjectLocality Address="10.1.1.144" DNSName="localhost"/>
<saml2:AuthnContext>
<saml2:AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport</saml2:AuthnContextClassRef>
</saml2:AuthnContext>
</saml2:AuthnStatement>
<saml2:AttributeStatement>
<saml2:Attribute Name="urn:oasis:names:tc:xspa:1.0:subject:subject-id">
<saml2:AttributeValue>John Doe</saml2:AttributeValue>
</saml2:Attribute>
<saml2:Attribute Name="urn:oasis:names:tc:xspa:1.0:subject:organization">
<saml2:AttributeValue>Dr. John M Doe, MD Practice</saml2:AttributeValue>
</saml2:Attribute>
<saml2:Attribute Name="urn:oasis:names:tc:xspa:1.0:subject:organization-id">
<saml2:AttributeValue></saml2:AttributeValue>
</saml2:Attribute>
<saml2:Attribute Name="urn:nhin:names:saml:homeCommunityId">
<saml2:AttributeValue></saml2:AttributeValue>
</saml2:Attribute>
<saml2:Attribute Name="urn:oasis:names:tc:xacml:2.0:subject:role">
<saml2:AttributeValue>
<Role xmlns="urn:hl7-org:v3" code="112247003" codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED CT" displayName="Medical doctor" xsi:type="CE"/>
</saml2:AttributeValue>
</saml2:Attribute>
<saml2:Attribute Name="urn:oasis:names:tc:xspa:1.0:subject:purposeofuse">
<saml2:AttributeValue>
<PurposeOfUse xmlns="urn:hl7-org:v3" code="TREATMENT" codeSystem="2.16.840.1.113883.3.18.7.1" codeSystemName="nhin-purpose" displayName="Treatment" xsi:type="CE"/>
</saml2:AttributeValue>
</saml2:Attribute>
<saml2:Attribute Name="urn:oasis:names:tc:xacml:2.0:resource:resource-id">
<saml2:AttributeValue></saml2:AttributeValue>
</saml2:Attribute>
</saml2:AttributeStatement>
</saml2:Assertion>
<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
<SignedInfo>
<CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
<SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
<Reference URI="#timestamp_ID">
<Transforms>
<Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
<Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
</Transforms>
<DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
<DigestValue></DigestValue>
</Reference>
</SignedInfo>
<SignatureValue></SignatureValue>
<KeyInfo>
<wsse:SecurityTokenReference xmlns:wsse11="http://docs.oasis-open.org/wss/oasis-wss-wssecurity-secext-1.1.xsd" wsse11:TokenType="http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0">
<wsse:KeyIdentifier ValueType="http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLID">assertion_ID</wsse:KeyIdentifier>
</wsse:SecurityTokenReference>
</KeyInfo>
</Signature>
</wsse:Security>
</env:Header>
<env:Body>
<PRPA_IN201305UV02 xmlns="urn:hl7-org:v3" ITSVersion="XML_1.0">
<id extension="126627497759" root="1.3.6.1.4.1.52618.1.3"/>
<creationTime value="20221013181817"/>
<interactionId extension="PRPA_IN201305UV02" root="2.16.840.1.113883.1.6"/>
<processingCode code="P"/>
<processingModeCode code="T"/>
<acceptAckCode code="AL"/>
<receiver typeCode="RCV">
<device classCode="DEV" determinerCode="INSTANCE">
<id root="0.0.0"/>
<telecom value="https://RH-Windows-TMP-b994dba9f85ba908.elb.us-east-1.amazonaws.com:4437/"/>
<asAgent classCode="AGNT">
<representedOrganization classCode="ORG" determinerCode="INSTANCE">
<id root=""/>
</representedOrganization>
</asAgent>
</device>
</receiver>
<sender typeCode="SND">
<device classCode="DEV" determinerCode="INSTANCE">
<id root="1.3.6.1.4.1.52618.1.2"/>
<asAgent classCode="AGNT">
<representedOrganization classCode="ORG" determinerCode="INSTANCE">
<id root="1.3.6.1.4.1.52618.1"/>
</representedOrganization>
</asAgent>
</device>
</sender>
<controlActProcess classCode="CACT" moodCode="EVN">
<code code="PRPA_TE201305UV02" codeSystem="2.16.840.1.113883.1.6"/>
<authorOrPerformer typeCode="AUT">
<assignedDevice classCode="ASSIGNED">
<id root="1.3.6.1.4.1.52618.1.1"/>
</assignedDevice>
</authorOrPerformer>
<queryByParameter>
<queryId extension="126627497760" root="1.3.6.1.4.1.52618.1.3.1"/>
<statusCode code="new"/>
<responseModalityCode code="R"/>
<responsePriorityCode code="I"/>
<parameterList>
<livingSubjectAdministrativeGender>
<value code="M"/>
<semanticsText>LivingSubject.administrativeGender</semanticsText>
</livingSubjectAdministrativeGender>
<livingSubjectBirthTime>
<value value=""/>
<semanticsText>LivingSubject.birthTime</semanticsText>
</livingSubjectBirthTime>
<livingSubjectId>
<value extension="" root="1.3.6.1.4.1.52618.1.1"/>
<semanticsText>LivingSubject.id</semanticsText>
</livingSubjectId>
<livingSubjectName>
<value>
<given></given>
<family>TEST</family>
</value>
<semanticsText>LivingSubject.name</semanticsText>
</livingSubjectName>
<patientAddress>
<value>
<streetAddressLine>Home Dr</streetAddressLine>
<city>Charlotte</city>
<state>NC</state>
<postalCode></postalCode>
<country>US</country>
</value>
<semanticsText>Patient.addr</semanticsText>
</patientAddress>
</parameterList>
</queryByParameter>
</controlActProcess>
</PRPA_IN201305UV02>
</env:Body>
</env:Envelope>
I am using rhino javascript and below is the code
//////////////////////////////////////////////////////////////////////////////////
// Generate our dynamic message values
//
var timestampId = UUIDGenerator.getUUID();
var assertionId = UUIDGenerator.getUUID();
var createdTimestamp = new Date().toISOString();
var expiresTimestamp = new Date((new Date()).getTime() + 10000*10).toISOString();
var samlenvelope="<env:Envelope xmlns:env=\"http://www.w3.org/2003/05/soap-envelope\">"+
"<env:Header xmlns:a=\"http://www.w3.org/2005/08/addressing\">"+
"<a:MessageID>urn:uuid:32886a29-98ad-4284-b00e-3fe4ded10d16</a:MessageID>"+
"<a:To env:mustUnderstand=\"true\"></a:To>"+
"<a:Action env:mustUnderstand=\"true\">urn:hl7-org:v3:PRPA_IN201305UV02:CrossGatewayPatientDiscovery</a:Action>"+
"<wsse:Security xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\" xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">"+
"<wsu:Timestamp wsu:Id=\"timestamp_ID\">"+
"<wsu:Created>2022-10-13T18:18:17.763Z</wsu:Created>"+
"<wsu:Expires>2023-10-13T18:23:17.763Z</wsu:Expires>"+
"</wsu:Timestamp>"+
"<saml2:Assertion xmlns:saml2=\"urn:oasis:names:tc:SAML:2.0:assertion\" xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ID=\"assertion_ID\" IssueInstant=\"2022-10-13T18:18:17.763Z\" Version=\"2.0\">"+
"<saml2:Issuer Format=\"urn:oasis:names:tc:SAML:2.0:nameid-format:X509SubjectName\"></saml2:Issuer>"+
"<saml2:Subject>"+
"<saml2:NameID Format=\"urn:oasis:names:tc:SAML:1.1:nameid-format:X509SubjectName\"></saml2:NameID>"+
"<saml2:SubjectConfirmation Method=\"urn:oasis:names:tc:SAML:2.0:cm:holder-of-key\">"+
"<saml2:SubjectConfirmationData>"+
"<KeyInfo xmlns=\"http://www.w3.org/2000/09/xmldsig#\">"+
"<KeyValue>"+
"<RSAKeyValue>"+
"<Modulus></Modulus>"+
"<Exponent>AQAB</Exponent>"+
"</RSAKeyValue>"+
"</KeyValue>"+
"</KeyInfo>"+
"</saml2:SubjectConfirmationData>"+
"</saml2:SubjectConfirmation>"+
"</saml2:Subject>"+
"<saml2:Conditions NotBefore=\"2022-10-13T18:15:17.763Z\" NotOnOrAfter=\"2022-10-13T18:23:17.763Z\">"+
"</saml2:Conditions>"+
"<saml2:AuthnStatement AuthnInstant=\"2022-10-13T17:55:17.743Z\" SessionIndex=\"1234567890\">"+
"<saml2:SubjectLocality Address=\"10.1.1.144\" DNSName=\"localhost\"/>"+
"<saml2:AuthnContext>"+
"<saml2:AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport</saml2:AuthnContextClassRef>"+
"</saml2:AuthnContext>"+
"</saml2:AuthnStatement>"+
"<saml2:AttributeStatement>"+
"<saml2:Attribute Name=\"urn:oasis:names:tc:xspa:1.0:subject:subject-id\">"+
"<saml2:AttributeValue>John Doe</saml2:AttributeValue>"+
"</saml2:Attribute>"+
"<saml2:Attribute Name=\"urn:oasis:names:tc:xspa:1.0:subject:organization\">"+
"<saml2:AttributeValue>Dr. John M Doe, MD Practice</saml2:AttributeValue>"+
"</saml2:Attribute>"+
"<saml2:Attribute Name=\"urn:oasis:names:tc:xspa:1.0:subject:organization-id\">"+
"<saml2:AttributeValue></saml2:AttributeValue>"+
"</saml2:Attribute>"+
"<saml2:Attribute Name=\"urn:nhin:names:saml:homeCommunityId\">"+
"<saml2:AttributeValue></saml2:AttributeValue>"+
"</saml2:Attribute>"+
"<saml2:Attribute Name=\"urn:oasis:names:tc:xacml:2.0:subject:role\">"+
"<saml2:AttributeValue>"+
"<Role xmlns=\"urn:hl7-org:v3\" code=\"112247003\" codeSystem=\"2.16.840.1.113883.6.96\" codeSystemName=\"SNOMED CT\" displayName=\"Medical doctor\" xsi:type=\"CE\"/>"+
"</saml2:AttributeValue>"+
"</saml2:Attribute>"+
"<saml2:Attribute Name=\"urn:oasis:names:tc:xspa:1.0:subject:purposeofuse\">"+
"<saml2:AttributeValue>"+
"<PurposeOfUse xmlns=\"urn:hl7-org:v3\" code=\"TREATMENT\" codeSystem=\"2.16.840.1.113883.3.18.7.1\" codeSystemName=\"nhin-purpose\" displayName=\"Treatment\" xsi:type=\"CE\"/>"+
"</saml2:AttributeValue>"+
"</saml2:Attribute>"+
"<saml2:Attribute Name=\"urn:oasis:names:tc:xacml:2.0:resource:resource-id\">"+
"<saml2:AttributeValue></saml2:AttributeValue>"+
"</saml2:Attribute>"+
"</saml2:AttributeStatement>"+
"</saml2:Assertion>"+
"</wsse:Security>"+
"</env:Header>"+
"<env:Body>"+
"<PRPA_IN201305UV02 xmlns=\"urn:hl7-org:v3\" ITSVersion=\"XML_1.0\">"+
"<id extension=\"126627497759\" root=\"1.3.6.1.4.1.52618.1.3\"/>"+
"<creationTime value=\"20221013181817\"/>"+
"<interactionId extension=\"PRPA_IN201305UV02\" root=\"2.16.840.1.113883.1.6\"/>"+
"<processingCode code=\"P\"/>"+
"<processingModeCode code=\"T\"/>"+
"<acceptAckCode code=\"AL\"/>"+
"<receiver typeCode=\"RCV\">"+
"<device classCode=\"DEV\" determinerCode=\"INSTANCE\">"+
"<id root=\"0.0.0\"/>"+
"<telecom value=\"https://RH-Windows-TMP-b994dba9f85ba908.elb.us-east-1.amazonaws.com:4437/\"/>"+
"<asAgent classCode=\"AGNT\">"+
"<representedOrganization classCode=\"ORG\" determinerCode=\"INSTANCE\">"+
"<id root=\"\"/>"+
"</representedOrganization>"+
"</asAgent>"+
"</device>"+
"</receiver>"+
"<sender typeCode=\"SND\">"+
"<device classCode=\"DEV\" determinerCode=\"INSTANCE\">"+
"<id root=\"1.3.6.1.4.1.52618.1.2\"/>"+
"<asAgent classCode=\"AGNT\">"+
"<representedOrganization classCode=\"ORG\" determinerCode=\"INSTANCE\">"+
"<id root=\"1.3.6.1.4.1.52618.1\"/>"+
"</representedOrganization>"+
"</asAgent>"+
"</device>"+
"</sender>"+
"<controlActProcess classCode=\"CACT\" moodCode=\"EVN\">"+
"<code code=\"PRPA_TE201305UV02\" codeSystem=\"2.16.840.1.113883.1.6\"/>"+
"<authorOrPerformer typeCode=\"AUT\">"+
"<assignedDevice classCode=\"ASSIGNED\">"+
"<id root=\"1.3.6.1.4.1.52618.1.1\"/>"+
"</assignedDevice>"+
"</authorOrPerformer>"+
"<queryByParameter>"+
"<queryId extension=\"\" root=\"1.3.6.1.4.1.52618.1.3.1\"/>"+
"<statusCode code=\"new\"/>"+
"<responseModalityCode code=\"R\"/>"+
"<responsePriorityCode code=\"I\"/>"+
"<parameterList>"+
"<livingSubjectAdministrativeGender>"+
"<value code=\"M\"/>"+
"<semanticsText>LivingSubject.administrativeGender</semanticsText>"+
"</livingSubjectAdministrativeGender>"+
"<livingSubjectBirthTime>"+
"<value value=\"\"/>"+
"<semanticsText>LivingSubject.birthTime</semanticsText>"+
"</livingSubjectBirthTime>"+
"<livingSubjectId>"+
"<value extension=\"\" root=\"1.3.6.1.4.1.52618.1.1\"/>"+
"<semanticsText>LivingSubject.id</semanticsText>"+
"</livingSubjectId>"+
"<livingSubjectName>"+
"<value>"+
"<given></given>"+
"<family>TEST</family>"+
"</value>"+
"<semanticsText>LivingSubject.name</semanticsText>"+
"</livingSubjectName>"+
"<patientAddress>"+
"<value>"+
"<streetAddressLine>Home Dr</streetAddressLine>"+
"<city>Charlotte</city>"+
"<state>NC</state>"+
"<postalCode></postalCode>"+
"<country>US</country>"+
"</value>"+
"<semanticsText>Patient.addr</semanticsText>"+
"</patientAddress>"+
"</parameterList>"+
"</queryByParameter>"+
"</controlActProcess>"+
"</PRPA_IN201305UV02>"+
"</env:Body>"+
"</env:Envelope>"+;
var samlString = new java.lang.String(samlenvelope);
////////////////////////////////////////////////////////////////////////////////////
// Build our XML DOM for signature
//
var documentBuilderFactory = javax.xml.parsers.DocumentBuilderFactory.newInstance();
documentBuilderFactory.setNamespaceAware(true);
var document = documentBuilderFactory.newDocumentBuilder().parse(new java.io.ByteArrayInputStream(samlString.getBytes("utf-8")));
////////////////////////////////////////////////////////////////////////////////////
// Configure Digital Signature utilities for required crypto operations
//
var xmlDsigFactory = javax.xml.crypto.dsig.XMLSignatureFactory.getInstance("DOM");
var parameterSpec = new javax.xml.crypto.dsig.spec.ExcC14NParameterSpec();
var reference = xmlDsigFactory.newReference
(
"#assertion_ID",
xmlDsigFactory.newDigestMethod(javax.xml.crypto.dsig.DigestMethod.SHA1, null),
java.util.Collections.singletonList(xmlDsigFactory.newTransform("http://www.w3.org/2001/10/xml-exc-c14n#", parameterSpec)),
null, //type
null //id
)
var signedInfo = xmlDsigFactory.newSignedInfo
(
xmlDsigFactory.newCanonicalizationMethod
(
javax.xml.crypto.dsig.CanonicalizationMethod.EXCLUSIVE,
parameterSpec
),
xmlDsigFactory.newSignatureMethod(javax.xml.crypto.dsig.SignatureMethod.RSA_SHA1, null),
java.util.Collections.singletonList(reference)
)
var reference1 = xmlDsigFactory.newReference
(
"#timestamp_ID",
xmlDsigFactory.newDigestMethod(javax.xml.crypto.dsig.DigestMethod.SHA1, null),
java.util.Collections.singletonList(xmlDsigFactory.newTransform("http://www.w3.org/2001/10/xml-exc-c14n#", parameterSpec)),
null, //type
null //id
)
var signedInfo1 = xmlDsigFactory.newSignedInfo
(
xmlDsigFactory.newCanonicalizationMethod
(
javax.xml.crypto.dsig.CanonicalizationMethod.EXCLUSIVE,
parameterSpec
),
xmlDsigFactory.newSignatureMethod(javax.xml.crypto.dsig.SignatureMethod.RSA_SHA1, null),
java.util.Collections.singletonList(reference1)
)
//////////////////////////////////////////////////////
// Fetch our certificate and key
//
var certificate;
try
{
var inputStream = new java.io.FileInputStream("test.crt");
var certificateFactory = java.security.cert.CertificateFactory.getInstance("X.509");
certificate = certificateFactory.generateCertificate(inputStream);
}
finally
{
if (inputStream != null)
inputStream.close();
}
var privateKey;
var keyFactory = java.security.KeyFactory.getInstance("RSA");
var keySpec = new java.security.spec.PKCS8EncodedKeySpec(java.nio.file.Files.readAllBytes(new java.io.File("private_key.der").toPath()));
privateKey = keyFactory.generatePrivate(keySpec);
////////////////////////////////////////////////////////
// Generate the KeyInfo for our signature
//
var keyInfoFactory = xmlDsigFactory.getKeyInfoFactory();
var x509Content = new java.util.ArrayList();
x509Content.add(certificate);
var x509Data = keyInfoFactory.newX509Data(x509Content);
var keyInfo = keyInfoFactory.newKeyInfo(java.util.Collections.singletonList(x509Data));
var signature = xmlDsigFactory.newXMLSignature(signedInfo, keyInfo);
var dsc = new javax.xml.crypto.dsig.dom.DOMSignContext(privateKey, document.getDocumentElement());
var rootEl = document.getDocumentElement();
rootEl.setIdAttribute("ID",true);
signature.sign(dsc);
var signature1 = xmlDsigFactory.newXMLSignature(signedInfo1, keyInfo1);
var dsc = new javax.xml.crypto.dsig.dom.DOMSignContext(privateKey, document.getDocumentElement());
signature1.sign(dsc);
/*
var newEle=document.createElement("Transform");
newEle.setAttribute('Algorithm', 'http://www.w3.org/2000/09/xmldsig#enveloped-signature');
document.getElementsByTagName("Transforms").item(0).appendChild(newEle);*/
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Define any formatting preferences get the signed document as a string
//
var transformerFactory = javax.xml.transform.TransformerFactory.newInstance();
var transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(javax.xml.transform.OutputKeys.OMIT_XML_DECLARATION, "yes");
var stringWriter = new java.io.StringWriter();
transformer.transform(new javax.xml.transform.dom.DOMSource(document), new javax.xml.transform.stream.StreamResult(stringWriter));
channelMap.put("soapMessage", stringWriter.toString());
when I run the code I get this error
Wrapped org.w3c.dom.DOMException: NOT_FOUND_ERR: An attempt is made to
reference a node in a context where it does not exist.
Will appreciate your help

Related

How to put And and OR filter type when RetrieveMultiple query is Fetch Expression

Please advice how to filter CRM/Model Driven App Unified Client Interface View using below same query expression in RetrieveMultiple plugin when input parameter query is of type Fetch Expression:
FilterExpression filter = new FilterExpression(LogicalOperator.Or);
string[] sourceChannel = new string[] { "Central Bank", "AECB" };
FilterExpression filter1 = new FilterExpression(LogicalOperator.And);
filter1.Conditions.Add(new ConditionExpression("sourcechannelidname", ConditionOperator.NotIn, sourceChannel));
filter1.Conditions.Add(new ConditionExpression("casetypecode", ConditionOperator.Equal, 1));
FilterExpression filter2 = new FilterExpression(LogicalOperator.And);
filter2.Conditions.Add(new ConditionExpression("sourcechannelidname", ConditionOperator.In, sourceChannel));
filter2.Conditions.Add(new ConditionExpression("valid", ConditionOperator.Equal, 1));
filter2.Conditions.Add(new ConditionExpression("casetypecode", ConditionOperator.Equal, 1));
FilterExpression filter3 = new FilterExpression(LogicalOperator.And);
filter3.Conditions.Add(new ConditionExpression("sourcechannelidname", ConditionOperator.In, sourceChannel));
filter3.Conditions.Add(new ConditionExpression("valid", ConditionOperator.Equal, 2));
filter3.Conditions.Add(new ConditionExpression("reopeningcount", ConditionOperator.GreaterThan, 0));
filter3.Conditions.Add(new ConditionExpression("casetypecode", ConditionOperator.Equal, 1));
FilterExpression filter4 = new FilterExpression(LogicalOperator.And);
filter4.Conditions.Add(new ConditionExpression("sourcechannelidname", ConditionOperator.In, sourceChannel));
filter4.Conditions.Add(new ConditionExpression("valid", ConditionOperator.Equal, 2));
filter4.Conditions.Add(new ConditionExpression("statecode", ConditionOperator.NotEqual, 0));
filter4.Conditions.Add(new ConditionExpression("casetypecode", ConditionOperator.Equal, 1));
filter.AddFilter(filter1);
filter.AddFilter(filter2);
filter.AddFilter(filter3);
filter.AddFilter(filter4);
qe.Criteria.AddFilter(filter);
I tried below by taking help from Microsoft documentation as described here:
https://learn.microsoft.com/en-us/powerapps/developer/data-platform/org-service/samples/modify-query-preoperation-stage
But I don't have any idea how to put And and OR filter type in below XML Document.
Any help or guidance would be appreciated a lot.
entityElement.Add(
new XElement("filter",
new XElement("condition",
new XAttribute("attribute", "sourcechannelidname"),
new XAttribute("operator", "not-in"), //not equal
new XElement("value", new XText("Central Bank")),
new XElement("value", new XText("AECB"))
),
new XElement("condition",
new XAttribute("attribute", "casetypecode"),
new XAttribute("operator", "eq"), //equal
new XAttribute("value", "1"), //Complaints
)
)
);
In FetchXml the expression you're trying to write is (see the type='and'):
<filter type='and' >
<condition attribute='sourcechannelidname' operator='not-in' >
<value>Central Bank</value>
<value>AECB</value>
</condition>
<condition attribute='casetypecode' operator='eq' value='1' >
</filter>
So I think you just need to specify an XAttribute on the "filter" XElement
entityElement.Add(
new XElement("filter",
new XAttribute("type", "and"),
new XElement("condition",
new XAttribute("attribute", "sourcechannelidname"),
new XAttribute("operator", "not-in"), //not equal
new XElement("value", new XText("Central Bank")),
new XElement("value", new XText("AECB"))
),
new XElement("condition",
new XAttribute("attribute", "casetypecode"),
new XAttribute("operator", "eq"), //equal
new XAttribute("value", "1"), //Complaints
)
)
);
XrmToolbox can now parse C# into a fetch expression. Just use the "View" menu and choose "QueryExpression" to get it to pull open the window, then type (or paste) your valid code into it and click "Parse" and it will turn it into FetchXml for you.
You didn't include the full fetchXml query, and I didn't recognize the field names, but I copied it to the OOTB incident query (since I knew it had a casetypecode field) and replaced the field names with the same type. I made them parameters so you can easily replace them with your own params. Here is the code I used:
// Instantiate QueryExpression query
var query = new QueryExpression("incident");
query.TopCount = 50;
// Add all columns to query.ColumnSet
query.ColumnSet.AllColumns = true;
FilterExpression filter = new FilterExpression(LogicalOperator.Or);
string[] sourceChannel = new string[] { "Central Bank", "AECB" };
var stringColName = "ticketnumber";
var intColName = "timezoneruleversionnumber";
var pickColName = "servicestage";
FilterExpression filter1 = new FilterExpression(LogicalOperator.And);
filter1.Conditions.Add(new ConditionExpression(stringColName, ConditionOperator.NotIn, sourceChannel));
filter1.Conditions.Add(new ConditionExpression("casetypecode", ConditionOperator.Equal, 1));
FilterExpression filter2 = new FilterExpression(LogicalOperator.And);
filter2.Conditions.Add(new ConditionExpression(stringColName, ConditionOperator.In, sourceChannel));
filter2.Conditions.Add(new ConditionExpression(pickColName , ConditionOperator.Equal, 1));
filter2.Conditions.Add(new ConditionExpression("casetypecode", ConditionOperator.Equal, 1));
FilterExpression filter3 = new FilterExpression(LogicalOperator.And);
filter3.Conditions.Add(new ConditionExpression(stringColName, ConditionOperator.In, sourceChannel));
filter3.Conditions.Add(new ConditionExpression(pickColName , ConditionOperator.Equal, 2));
filter3.Conditions.Add(new ConditionExpression(intColName, ConditionOperator.GreaterThan, 0));
filter3.Conditions.Add(new ConditionExpression("casetypecode", ConditionOperator.Equal, 1));
FilterExpression filter4 = new FilterExpression(LogicalOperator.And);
filter4.Conditions.Add(new ConditionExpression(stringColName, ConditionOperator.In, sourceChannel));
filter4.Conditions.Add(new ConditionExpression(pickColName , ConditionOperator.Equal, 2));
filter4.Conditions.Add(new ConditionExpression("statecode", ConditionOperator.NotEqual, 0));
filter4.Conditions.Add(new ConditionExpression("casetypecode", ConditionOperator.Equal, 1));
filter.AddFilter(filter1);
filter.AddFilter(filter2);
filter.AddFilter(filter3);
filter.AddFilter(filter4);
query.Criteria.AddFilter(filter);
and this is the filter it created:
<filter type="and" >
<filter type="or" >
<filter type="and" >
<condition attribute="ticketnumber" operator="not-in" >
<value>Central Bank</value>
<value>AECB</value>
</condition>
<condition attribute="casetypecode" operator="eq" value="1" />
</filter>
<filter type="and" >
<condition attribute="ticketnumber" operator="in" >
<value>Central Bank</value>
<value>AECB</value>
</condition>
<condition attribute="servicestage" operator="eq" value="1" />
<condition attribute="casetypecode" operator="eq" value="1" />
</filter>
<filter type="and" >
<condition attribute="ticketnumber" operator="in" >
<value>Central Bank</value>
<value>AECB</value>
</condition>
<condition attribute="servicestage" operator="eq" value="2" />
<condition attribute="timezoneruleversionnumber" operator="gt" value="0" />
<condition attribute="casetypecode" operator="eq" value="1" />
</filter>
<filter type="and" >
<condition attribute="ticketnumber" operator="in" >
<value>Central Bank</value>
<value>AECB</value>
</condition>
<condition attribute="servicestage" operator="eq" value="2" />
<condition attribute="statecode" operator="ne" value="0" />
<condition attribute="casetypecode" operator="eq" value="1" />
</filter>
</filter>
</filter>

Verifying Signed Xml Generated From Java In NET

I have the below XML,
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Response xmlns="http://www.site.ae/g">
<Message xml:id="message">
<Header>
<Service>Read</Service>
<Action>SomeAction</Action>
</Header>
<Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="SomeDataType">
<Status>Success</Status>
<Data>
<Id>123</Id>
</Data>
</Body>
</Message>
<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
<SignedInfo>
<CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments"/>
<SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"/>
<Reference URI="#message">
<Transforms>
<Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
</Transforms>
<DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/>
<DigestValue>SomeValue</DigestValue>
</Reference>
</SignedInfo>
<SignatureValue>
SomeValue
</SignatureValue>
<KeyInfo>
<X509Data>
<X509Certificate>
SomeValue
</X509Certificate>
</X509Data>
</KeyInfo>
</Signature>
</Response>
The above XML genereted from a java application. The java application team provided us 3 certificate to verify the above xml. I have created 3 objects in C#,
var clientCert = new X509Certificate2("clientCert.cer");
var intermediateCert = new X509Certificate2("intermediateCert.cer");
var rootCert = new X509Certificate2("rootCert.cer");
One is root, second one is intermediate and third one is certificate. I have created the below code,
var xmlDoc = new XmlDocument();
xmlDoc.PreserveWhitespace = true;
xmlDoc.Load("above.xml");
bool result = VerifyXml(xmlDoc, clientCert);
private static Boolean VerifyXml(XmlDocument Doc, X509Certificate2 Key)
{
// Create a new SignedXml object and pass it
// the XML document class.
var signedXml = new System.Security.Cryptography.Xml.SignedXml(Doc);
// Find the "Signature" node and create a new XmlNodeList object.
XmlNodeList nodeList = Doc.GetElementsByTagName("Signature");
// Throw an exception if no signature was found.
if (nodeList.Count <= 0)
{
throw new CryptographicException("Verification failed: No Signature was found in the document.");
}
// Though it is possible to have multiple signatures on
// an XML document, this app only supports one signature for
// the entire XML document. Throw an exception
// if more than one signature was found.
if (nodeList.Count >= 2)
{
throw new CryptographicException("Verification failed: More that one signature was found for the document.");
}
// Load the first <signature> node.
signedXml.LoadXml((XmlElement)nodeList[0]);
// Check the signature and return the result.
return signedXml.CheckSignature(Key, true);
}
But the above code result is always return false. Is there is something I am missing? Is .NET support verifying the xml generated from java?
Got Answer from
Verify SignatureValue And DigestValue Using Sha256 RSA

Wildfly14 + Unable to lookup invm queue

Unable to lookup invm queue thru ConnectionFactory
Hashtable<String, Object> properties = new Hashtable<>();
properties.put("connectionFactory.ConnectionFactory", "(tcp://localhost:8080)?httpUpgradeEnabled=true&retryInterval=3000&reconnectAttempts=-1&initialConnectAttempts=10&maxRetryInterval=3000&clientFailureCheckPeriod=1000");
properties.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.activemq.artemis.jndi.ActiveMQInitialContextFactory");
InitialContext jndiContext = new InitialContext(properties);
ConnectoryFactory connFactory = (ConnectionFactory) jndiContext.lookup(connectionFactory);
Connection connection = connFactory.createConnection(userName, password);
session = connection.createSession(true, javax.jms.Session.AUTO_ACKNOWLEDGE);
Hashtable<String, Object> properties = new Hashtable<>();
properties.put(Context.INITIAL_CONTEXT_FACTORY, factoryInitial);
InitialContext ctx = new InitialContext(properties);
destination = (Destination) ctx.lookup("dynamicQueues/TestQueue"); //I can't put queue name in jndi.properties
MessageProducer producer = session.createProducer(destination);
producer.send(message, Message.DEFAULT_DELIVERY_MODE, Message.DEFAULT_PRIORITY, msgTTL);
if (session.getTransacted() && session.getAcknowledgeMode() == Session.SESSION_TRANSACTED) {
session.commit();
}
When I execute the above code then it throws error saying that Queue "TestQueue" does not exists. I have tried with lookup queue with dynamicQueues/TestQueue and jms/TestQueue but in both cases I got same error
Can you please let me know what is wrong with this code.
Please find below Wildfly ActiveMQ Artemis configuration
<server name="default" persistence-enabled="true">
<cluster password="${jboss.messaging.cluster.password:CHANGE ME!!}"/>
<bindings-directory path="/opt/shared/messaging/live/bindings"/>
<journal-directory path="/opt/shared/messaging/live/journal"/>
<large-messages-directory path="/opt/shared/messaging/live/largemessages"/>
<paging-directory path="/opt/shared/messaging/live/paging"/>
<security-setting name="#">
<role name="guest" send="true" consume="true" create-durable-queue="true" delete-durable-queue="true" create-non-durable-queue="true" delete-non-durable-queue="true"/>
</security-setting>
<address-setting name="#" dead-letter-address="jms.queue.DLQ" expiry-address="jms.queue.ExpiryQueue" redelivery-delay="60000" max-delivery-attempts="5" max-size-bytes="50485760" page-size-bytes="10485760" address-full-policy="PAGE" redistribution-delay="1000"/>
<http-connector name="http-connector" socket-binding="http" endpoint="http-acceptor"/>
<http-connector name="http-connector-throughput" socket-binding="http" endpoint="http-acceptor-throughput">
<param name="batch-delay" value="50"/>
</http-connector>
<in-vm-connector name="in-vm" server-id="0">
<param name="buffer-pooling" value="false"/>
</in-vm-connector>
<http-acceptor name="http-acceptor" http-listener="default"/>
<http-acceptor name="http-acceptor-throughput" http-listener="default">
<param name="batch-delay" value="50"/>
<param name="direct-deliver" value="false"/>
</http-acceptor>
<in-vm-acceptor name="in-vm" server-id="0">
<param name="buffer-pooling" value="false"/>
</in-vm-acceptor>
<broadcast-group name="bg-group1" jgroups-cluster="activemq-cluster" connectors="http-connector"/>
<discovery-group name="dg-group1" jgroups-cluster="activemq-cluster"/>
<cluster-connection name="my-cluster" address="jms" connector-name="http-connector" discovery-group="dg-group1"/>
<jms-queue name="ExpiryQueue" entries="java:/jms/queue/ExpiryQueue"/>
<jms-queue name="DLQ" entries="java:/jms/queue/DLQ"/>
<jms-queue name="TestQueue" entries="java:/jms/TestQueue java:jboss/exported/jms/TestQueue"/>
<connection-factory name="InVmConnectionFactory" entries="java:/ConnectionFactory" connectors="in-vm"/>
<connection-factory name="RemoteConnectionFactory" entries="java:jboss/exported/jms/RemoteConnectionFactory" connectors="http-connector" ha="true" block-on-acknowledge="true" reconnect-attempts="-1"/>
<pooled-connection-factory name="activemq-ra" entries="java:/JmsXA java:jboss/DefaultJMSConnectionFactory" connectors="in-vm" transaction="xa"/>
</server>
I just want to share some links with you, for further reading.
The quickstarts are a good entry point if you start developing with wildfly.
Here you have an external client example:
https://github.com/wildfly/quickstart/tree/14.x/helloworld-jms
Here one where it everything runs inside the wildfly container:
https://github.com/wildfly/quickstart/tree/14.x/helloworld-mdb
Here you have general documentation about messaging in wildfly 14:
https://docs.wildfly.org/14/Admin_Guide.html#Messaging
The initial context factory you're using (i.e. org.apache.activemq.artemis.jndi.ActiveMQInitialContextFactory) is a client-side only JNDI implementation for use with standalone ActiveMQ Artemis. Since you are using Wildfly you should be using their JNDI implementation (i.e. org.wildfly.naming.client.WildFlyInitialContextFactory). Then you can lookup both the connection factory and the destination from the Wildfly server and you won't need to specify the connection factory URL in your code.
Also, there is no such thing as an "invm queue".

KSOAP2 complex request property not being seen

I'm having a problem sending a complex SOAP request to a third-party company server (server can have no changes) from an android device. I'm using KSOAP2 library and one of the properties is missing (server is giving an error which occurs when klausimai is null. Also the same namespace in my request is repeated multiple times when KSOAP2 generates the XML, since I pass a lot of PropertyInfo. My question is, why could the server see other properties (it would also give an error about the null ones) But doesn't see klausimai ?
Sample request XML for WS given by server company
?xml version="1.0" encoding="UTF-8"?>
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
<teiktiTemineAtaskaita xmlns="http://tempuri.org/">
<userName>apps</userName>
<password>mob2015*</password>
<uzduotiesNr>24287</uzduotiesNr>
<inspektavimas xmlns:a="http://schemas.datacontract.org/2004/07/DssisMP" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<a:apsilankymuObjekteSkaicius i:nil="true" />
<a:atstovai i:nil="true" />
<a:darbdavioBuveinesAdresas i:nil="true" />
<a:darbdavioGimimoData i:nil="true" />
<a:darbdavioKodas>110871120</a:darbdavioKodas>
<a:darbdavioLytis i:nil="true" />
<a:darbdavioPagrindineEkonomineVeikla i:nil="true" />
<a:darbdavioPavadinimas i:nil="true" />
<a:darbdavioPavarde i:nil="true" />
<a:darbdavioTipas i:nil="true" />
<a:darbdavioVardas i:nil="true" />
<a:inspektavimoNr>11112245</a:inspektavimoNr>
<a:inspektavimoPradzia>2015-07-23T00:00:00+03:00</a:inspektavimoPradzia>
<a:inspektavimoTiksloKodas>111</a:inspektavimoTiksloKodas>
<a:institucijos i:nil="true" />
<a:savivaldybesKodas i:nil="true" />
<a:temineAtaskaita>
<a:klausimai>
<a:TAKlausimas>
<a:atsakymas>2</a:atsakymas>
<a:eilNr>1.</a:eilNr>
<a:klausimas i:nil="true" />
<a:kodas>1000</a:kodas>
<a:komentaras i:nil="true" />
</a:TAKlausimas>
<a:TAKlausimas>
<a:atsakymas>1</a:atsakymas>
<a:eilNr>1.1.</a:eilNr>
<a:klausimas i:nil="true" />
<a:kodas>1001</a:kodas>
<a:komentaras i:nil="true" />
</a:TAKlausimas>
<a:TAKlausimas>
<a:atsakymas>3</a:atsakymas>
<a:eilNr>2.</a:eilNr>
<a:klausimas i:nil="true" />
<a:kodas>1002</a:kodas>
<a:komentaras i:nil="true" />
</a:TAKlausimas>
</a:klausimai>
<a:nr>BIOCIDŲ PRIEŽIŪRA-0050-0007</a:nr>
<a:rekomendacijos i:nil="true" />
<a:surasymoData>2015-07-23T00:00:00+03:00</a:surasymoData>
<a:tipas>9</a:tipas>
</a:temineAtaskaita>
<a:tikrintaEkonomineVeikla i:nil="true" />
<a:tikrintaNakti i:nil="true" />
<a:tikrintasObjektas i:nil="true" />
<a:tikrintoObjektoAdresas i:nil="true" />
<a:tikrintoObjektoPavadinimas i:nil="true" />
<a:vadovoAsmensKodas i:nil="true" />
<a:vadovoGimimoData i:nil="true" />
<a:vadovoLytis i:nil="true" />
<a:vadovoPareigos i:nil="true" />
<a:vadovoPavarde i:nil="true" />
<a:vadovoVardas i:nil="true" />
</inspektavimas>
</teiktiTemineAtaskaita>
</s:Body>
</s:Envelope>
My HTTPTransport request dump XML generated by KSOAP2
<?xml version="1.0" encoding="UTF-8"?>
<v:Envelope xmlns:v="http://schemas.xmlsoap.org/soap/envelope/" xmlns:c="http://schemas.xmlsoap.org/soap/encoding/" xmlns:d="http://www.w3.org/2001/XMLSchema" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<v:Header />
<v:Body>
<teiktiTemineAtaskaita xmlns="http://tempuri.org/">
<userName>apps</userName>
<password>mob2015*</password>
<uzduotiesNr>212855</uzduotiesNr>
<n0:inspektavimas xmlns:n0="http://tempuri.org/">
<inspektavimoNr i:null="true" />
<n1:inspektavimoPradzia xmlns:n1="http://schemas.datacontract.org/2004/07/DssisMP" i:type="d:dateTime">2015-07-26T21:00:00.000Z</n1:inspektavimoPradzia>
<inspektavimoTiksloKodas>1101</inspektavimoTiksloKodas>
<darbdavioKodas>120163917</darbdavioKodas>
<darbdavioPavadinimas>Statybos ir remonto uždaroji akcinė bendrovė "RISTATYBA"</darbdavioPavadinimas>
<darbdavioTipas>1</darbdavioTipas>
<darbdavioBuveinesAdresas i:null="true" />
<darbdavioPagrindineEkonomineVeikla i:null="true" />
<vadovoAsmensKodas>721788222</vadovoAsmensKodas>
<vadovoVardas>tvt</vadovoVardas>
<vadovoPavarde>gtvt</vadovoPavarde>
<vadovoPareigos>5</vadovoPareigos>
<n2:vadovoGimimoDiena xmlns:n2="http://schemas.datacontract.org/2004/07/DssisMP" i:type="d:dateTime">2015-07-22T21:00:00.000Z</n2:vadovoGimimoDiena>
<vadovoLytis>0</vadovoLytis>
<tikrintasObjektas>3</tikrintasObjektas>
<tikrintoObjektoPavadinimas i:null="true" />
<tikrintoObjektoAdresas i:null="true" />
<savivaldybesKodas>46</savivaldybesKodas>
<tikrintaEkonomineVeikla i:null="true" />
<apsilankymuObjekteSkaicius i:null="true" />
<tikrintaNakti>0</tikrintaNakti>
<n3:temineAtaskaita xmlns:n3="http://schemas.datacontract.org/2004/07/DssisMP">
<n3:nr i:null="true" />
<n3:tipas i:type="d:int">18</n3:tipas>
<n3:surasymoData i:type="d:dateTime">2015-07-22T09:53:59.822Z</n3:surasymoData>
<n3:klausimai>
<n3:TAKlausimas>
<n3:kodas i:type="d:string">3183</n3:kodas>
<n3:eilNr i:type="d:string">1.1.</n3:eilNr>
<n3:klausimas i:null="true" />
<n3:atsakymas i:type="d:int">1</n3:atsakymas>
<n3:komentaras i:null="true" />
</n3:TAKlausimas>
<n3:TAKlausimas>
<n3:kodas i:type="d:string">3184</n3:kodas>
<n3:eilNr i:type="d:string">1.1.1.</n3:eilNr>
<n3:klausimas i:null="true" />
<n3:atsakymas i:type="d:int">2</n3:atsakymas>
<n3:komentaras i:null="true" />
</n3:TAKlausimas>
</n3:klausimai>
<n3:rekomendacijos i:type="d:string">Gyghugyb</n3:rekomendacijos>
</n3:temineAtaskaita>
</n0:inspektavimas>
</teiktiTemineAtaskaita>
</v:Body>
</v:Envelope>
My Java code for request creation
List<Questionnaire> questionnaireList = new ArrayList<>();
String METHOD_NAME = "teiktiTemineAtaskaita";
String SOAP_ACTION = "http://tempuri.org/IDssisMP/" + METHOD_NAME;
String A_NAMESPACE = "http://schemas.datacontract.org/2004/07/DssisMP";
String I_NAMESPACE = "http://www.w3.org/2001/XMLSchema-instance";
String NAMESPACE = "http://tempuri.org/";
String URL = "http://dvs/dssis_ws_test/DssisMP.svc";
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
UserInfo userInfo = UserInfo.getAll().get(0);
request.addProperty("userName", userInfo.getUserName());
request.addProperty("password", userInfo.getPassword());
request.addProperty("uzduotiesNr", taskId);
CompanyInfo ci = CompanyInfo.getByTaskCompanyId(taskId, companyId);
if (ci == null) {
sendResponseFailed(responseHandler);
//starter validation
} else {
//adding all the non-complex properties
SoapObject inspektavimas = new SoapObject(NAMESPACE, "inspektavimas");
if (ci.getInspectationId() != 0) {
inspektavimas.addProperty("inspektavimoNr", ci.getInspectationId());
} else {
inspektavimas.addProperty("inspektavimoNr", null);
}
if (ci.getDateInspectation() != null) {
PropertyInfo p = new PropertyInfo();
p.setNamespace(A_NAMESPACE);
p.setName("inspektavimoPradzia");
p.setType(MarshalDate.class);
p.setValue(ci.getDateInspectation());
inspektavimas.addProperty(p);
} else {
sendResponseFailed(responseHandler);
}
if (ci.getGoalId() != 0) {
inspektavimas.addProperty("inspektavimoTiksloKodas", ci.getGoalId());
} else {
sendResponseFailed(responseHandler);
}
if (ci.getObjectName() != null) {
inspektavimas.addProperty("tikrintoObjektoPavadinimas", ci.getObjectName());
} else { inspektavimas.addProperty("tikrintoObjektoPavadinimas", null);
}
if (ci.getObjectAddress() != null) {
inspektavimas.addProperty("tikrintoObjektoAdresas", ci.getObjectAddress());
} else {
inspektavimas.addProperty("tikrintoObjektoAdresas", null);
}
//...
SoapObject soTemineAtaskaita = new SoapObject(A_NAMESPACE, "temineAtaskaita");
TemineAtaskaita temineAtaskaita = TemineAtaskaita.getByTaskCompanyThemeCode(taskId, companyId, themeCode);
PropertyInfo p = new PropertyInfo();
p.setNamespace(A_NAMESPACE);
p.setName("nr");
if (temineAtaskaita != null && temineAtaskaita.getAtaskaitosNr() != null) {
p.setValue(temineAtaskaita.getAtaskaitosNr());
soTemineAtaskaita.addProperty(p);
} else {
p.setValue(null);
soTemineAtaskaita.addProperty(p);
}
Theme theme = Theme.getByTaskCompanyThemeCode(taskId, companyId, themeCode);
if (theme != null) {
PropertyInfo pType = new PropertyInfo();
pType.setNamespace(A_NAMESPACE);
pType.setName("tipas");
pType.setValue(theme.getThemeCode());
soTemineAtaskaita.addProperty(pType);
PropertyInfo pDate = new PropertyInfo();
pDate.setNamespace(A_NAMESPACE);
pDate.setName("surasymoData");
pDate.setValue(theme.getDate());
pDate.setType(MarshalDate.class);
soTemineAtaskaita.addProperty(pDate);
}
//adding klausimai property which is not seen
SoapObject klausimai = new SoapObject(A_NAMESPACE, "klausimai");
List <Answer> answers = Answer.getByTaskCompanyThemeCode(taskId, companyId, themeCode);
for (Answer answer : answers) {
SoapObject soTAKlausimas = new SoapObject(A_NAMESPACE, "TAKlausimas");
PropertyInfo pCode = new PropertyInfo();
pCode.setNamespace(A_NAMESPACE);
pCode.setName("kodas");
pCode.setValue(answer.getQuestionId());
soTAKlausimas.addProperty(pCode);
Questionnaire questionnaire = Questionnaire.getById(answer.getQuestionId()).get(0);
PropertyInfo pEilNr = new PropertyInfo();
pEilNr.setNamespace(A_NAMESPACE);
pEilNr.setName("eilNr");
pEilNr.setValue(questionnaire.getPosition());
soTAKlausimas.addProperty(pEilNr);
PropertyInfo pKlausimas = new PropertyInfo();
pKlausimas.setNamespace(A_NAMESPACE);
pKlausimas.setName("klausimas");
pKlausimas.setValue(null);
soTAKlausimas.addProperty(pKlausimas);
PropertyInfo pAnswer = new PropertyInfo();
pAnswer.setNamespace(A_NAMESPACE);
pAnswer.setName("atsakymas");
pAnswer.setValue(questionnaire.getPosition());
if (answer.getAnswer() == QuestionItem.STATUS.YES.ordinal())
pAnswer.setValue(1);
else if (answer.getAnswer() == QuestionItem.STATUS.NO.ordinal())
pAnswer.setValue(2);
else if (answer.getAnswer() == QuestionItem.STATUS.UNKNOWN.ordinal())
pAnswer.setValue(3);
else if (answer.getAnswer() == QuestionItem.STATUS.PLAIN.ordinal())
pAnswer.setValue(null);
soTAKlausimas.addProperty(pAnswer);
PropertyInfo pComment = new PropertyInfo();
pComment.setNamespace(A_NAMESPACE);
pComment.setName("komentaras");
if (answer.getComment() != null && !answer.getComment().replace(" ", "").replace(" ", "").isEmpty()) {
pComment.setValue(answer.getComment());
} else {
pComment.setValue(null);
}
soTAKlausimas.addProperty(pComment);
klausimai.addSoapObject(soTAKlausimas);
}
soTemineAtaskaita.addSoapObject(klausimai);
if (theme != null) {
PropertyInfo pSuggestions = new PropertyInfo();
pSuggestions.setNamespace(A_NAMESPACE);
pSuggestions.setName("rekomendacijos");
if (theme.getSuggestions() != null && !theme.getSuggestions().replace(" ", "").replace(" ", "").isEmpty()) {
pSuggestions.setValue(theme.getSuggestions());
} else {
pSuggestions.setValue(null);
}
soTemineAtaskaita.addProperty(pSuggestions);
}
inspektavimas.addSoapObject(soTemineAtaskaita);
request.addSoapObject(inspektavimas);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setAddAdornments(false);
envelope.implicitTypes = true;
envelope.setOutputSoapObject(request);
new MarshalDate().register(envelope);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL, 45 * 1000);
androidHttpTransport.debug = true;
androidHttpTransport.call(SOAP_ACTION, envelope);
final SoapObject response = (SoapObject) envelope.getResponse();
****//...****
}
Well as it turns out, I managed to work together with server company, and the problem was ordering inside temineAtaskaita tag. klausimai property should have been the first property to give, althought outside in inspektavimas tag, ordering is not important and that is confusing.
Other problem now occurs is that, everything inside inspektavimas is null because the properties have no namespace. And adding them as PropertyInfo gives a lot of repeated namespaces (n0, n1,...,n20) in XML request Dump and server doesn't handle it. But this is another problem.

What is the correct format for SAML 2.0 Assertions?

We have a customer trying to use ADFS to SSO on to our web application. We are using the ComponentSpace SAML 2.0 library. The assertion being sent to us looks like:
<Assertion ID="_b8a24809-ab6b-4acd-ad6a-8bcb97bb1889" IssueInstant="2012-05-24T13:30:33.917Z" Version="2.0" xmlns="urn:oasis:names:tc:SAML:2.0:assertion">
<Issuer>http://example.com/adfs/services/trust</Issuer>
<Subject>
<NameID Format="urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress">mail#example.com</NameID>
<SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer">
<SubjectConfirmationData NotOnOrAfter="2012-05-24T13:35:33.920Z" Recipient="https://example.com/default.aspx" />
</SubjectConfirmation>
</Subject>
<Conditions NotBefore="2012-05-24T13:30:33.907Z" NotOnOrAfter="2012-05-24T14:30:33.907Z">
<AudienceRestriction>
<Audience>https://example.com</Audience>
</AudienceRestriction>
</Conditions>
<AttributeStatement>
<Attribute Name="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress">
<AttributeValue>mail#example.com</AttributeValue>
</Attribute>
</AttributeStatement>
<AuthnStatement AuthnInstant="2012-05-24T13:30:33.756Z" SessionIndex="_b8a24809-ab6b-4acd-ad6a-8bcb97bb1889">
<AuthnContext>
<AuthnContextClassRef>urn:federation:authentication:windows</AuthnContextClassRef>
</AuthnContext>
</AuthnStatement>
</Assertion>
The ComponentSpace library is pulling the full SamlResponse from the HTTP post but it reports no Assertions (ie samlResponse.GetAssertions().Count == 0). If I use the ComponentSpace examples it works but I notice all of the elements I build with the ComponentSpace library are prefixed with "saml:" (as I believe it should be).
Should the ComponentSpace library be able to find the Assertion without the saml: prefix or is there a way to configure ADFS to send it correctly?
A correct SAML response should contain namespace-qualified elements
<saml2p:Response Destination="https://www.google.com/a/squaresquare.biz/acs" IssueInstant="2010-08-04T17:47:20.956Z" xmlns:saml2p="urn:oasis:names:tc:SAML:2.0:protocol" InResponseTo="djfnhepndikoonjjkeomgplmkjofobhdbdieihpa" Version="2.0" ID="_bd24b4a3514fd93800d2a43cafc98edb">
<saml2:Issuer xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity">http://my.ssodemo.url.demo.google.com/idp/shibboleth</saml2:Issuer>
<ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
<ds:SignedInfo>
<ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"></ds:CanonicalizationMethod>
<ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"></ds:SignatureMethod>
<ds:Reference URI="#_bd24b4a3514fd93800d2a43cafc98edb">
<ds:Transforms>
<ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"></ds:Transform>
<ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#">
<ec:InclusiveNamespaces xmlns:ec="http://www.w3.org/2001/10/xml-exc-c14n#" PrefixList="dssaml2saml2p"></ec:InclusiveNamespaces>
</ds:Transform>
</ds:Transforms>
<ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"></ds:DigestMethod>
<ds:DigestValue>m/lUCS3nvfGuSJFKAtIz+ZrfxTU=</ds:DigestValue>
</ds:Reference>
</ds:SignedInfo>
<ds:SignatureValue>PLdYgU9u5KirVrMHNSwYvk6fQ401dMbpuiDXpapKf0eOKC6pN3g7tnTEzvfOaXhkDNXVmGN+lXQ6iUDppWpdO2MbvPVZabOBPU1aAO+CWI53ciC0rYsxpFzQLLMC/7x9Wk7VFFmYEecxAJV+lTWvp8ZKXvwqZbhiTO/23EC0xconGhnwSvKjJWQuLnMMaFWSjDFYyzgsp34cR7aX/eqhhJyA/rr2uFdmgEdagAl+/17ppgHgthgK+PJtX16AALtsoXonv6uybRCX/YiDRvM1VsdwusVq5tXh9V+bTMZcgi/3Eh+Em/OZp0En8pqOngvL19U4LfqG0yJZjoDGkpHuhA==</ds:SignatureValue>
<ds:KeyInfo>
<ds:X509Data>
<ds:X509Certificate>MIIDgjCCAmqgAwIBAgIVAKgIqbzZl7+0p2qjxJFVJs3DE/jxMA0GCSqGSIb3DQEBBQUAMDAxLjAsBgNVBAMTJWh0dHA6Ly93cGgtdWJpcTI3LmhvdC5jb3JwLmdvb2dsZS5jb20wHhcNMTAwNzIxMTcxNTA5WhcNMzAwNzIxMTcxNTA5WjAwMS4wLAYDVQQDEyVodHRwOi8vd3BoLXViaXEyNy5ob3QuY29ycC5nb29nbGUuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAioQsJycRmjPjB2xlH0iSGn14lNbO/jIVgiGIlzZwlPkH1s2TTdwoTKKQBSe2s8AnJ4LliXlne/qWun3peYht0+RhejtB20L+Bw/I+iKQBGpHzgIKdkPGZnemWl9KqWQ/ZYKnY2x6qMEBmhUfYZcawzs26em5a+iaYlrTJNVEZ+QwWvg2/EOJvJNyBkSfXyxia5eAHV38Uy7xn0G5Zc9ge4ckCYj6b8a/UxpPJM61KztzY5coDwReQsDBq+DciGALJPbFk4783TW...etc.etc</ds:X509Certificate>
</ds:X509Data>
</ds:KeyInfo>
</ds:Signature>
<saml2p:Status>
<saml2p:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"></saml2p:StatusCode>
</saml2p:Status>
<saml2:Assertion xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" Version="2.0" IssueInstant="2010-08-04T17:47:20.956Z" ID="_73fe28bcbb68e93df954d8e2f25097b1">
<saml2:Issuer Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity">http://my.ssodemo.url.demo.google.com/idp/shibboleth</saml2:Issuer>
<saml2:Subject>
<saml2:NameID Format="urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified">my_username</saml2:NameID>
<saml2:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer">
<saml2:SubjectConfirmationData NotOnOrAfter="2010-08-04T17:52:20.956Z" InResponseTo="djfnhepndikoonjjkeomgplmkjofobhdbdieihpa" Recipient="https://www.google.com/a/squaresquare.biz/acs" Address="172.24.6.38"></saml2:SubjectConfirmationData>
</saml2:SubjectConfirmation>
</saml2:Subject>
<saml2:Conditions NotOnOrAfter="2010-08-04T17:52:20.956Z" NotBefore="2010-08-04T17:47:20.956Z">
<saml2:AudienceRestriction>
<saml2:Audience>google.com</saml2:Audience>
</saml2:AudienceRestriction>
</saml2:Conditions>
<saml2:AuthnStatement SessionIndex="f306dd2bff4e9b3ba9218bd70fbaa87404d38a4c79547ac1edc9436a9f222213" AuthnInstant="2010-08-04T17:47:20.953Z">
<saml2:SubjectLocality Address="172.24.6.38"></saml2:SubjectLocality>
<saml2:AuthnContext>
<saml2:AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport</saml2:AuthnContextClassRef>
</saml2:AuthnContext>
</saml2:AuthnStatement>
</saml2:Assertion>
</saml2p:Response>
Namespace qualifications are optional.
It turns out that the above XML is valid (ADFS adds the namespace to the overall XML but not each element). The problem was that the ComponentSpace library has different methods for getting Signed or Encrypted Assertions and I was just calling the generic GetAssertions. ADFS was generating signed assertions and I needed to call the other function.
Here is the code we ended up with:
IList<EncryptedAssertion> encryptedAssertions = samlResponse.GetEncryptedAssertions();
if (encryptedAssertions.Count > 0 && x509Certificate != null) {
// Decrypt the assertion
EncryptedAssertion encryptedAssertion = encryptedAssertions[0];
XmlElement decryptedElement = encryptedAssertion.DecryptToXml(x509Certificate, null);
LogMessage("Decrypted assertion: " + decryptedElement.OuterXml);
// Then verify the signature.
VerifySignature(x509Certificate, decryptedElement);
samlAssertion = new SAMLAssertion(decryptedElement);
} else {
if (samlResponse.GetSignedAssertions().Count > 0) {
// Get the signed assertion and verify the signature.
XmlElement signedAssertionElement = samlResponse.GetSignedAssertions()[0];
LogMessage("Signed assertion: " + signedAssertionElement.OuterXml);
VerifySignature(x509Certificate, signedAssertionElement);
samlAssertion = new SAMLAssertion(signedAssertionElement);
} else {
// Assertion is not encrypted or signed.
if (samlResponse.GetAssertions().Count > 0) {
samlAssertion = samlResponse.GetAssertions()[0];
LogMessage("Assertion: " + samlAssertion.ToXml().OuterXml);
} else {
LogFatalError("No assertions in response");
}
}
}