Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
206 views
in Technique[技术] by (71.8m points)

SAML Assertion in a XML using C#

Here is the problem I am facing and need some help/guidance on this.

I have generated a XML message from my engine and this needs to be parsed to a service. In order to do that I have to change that message to SOAP message and insert SAML token on it. I am trying to perform this action using C# code. Below is the Input message which I have generated and the expected output of this:

Input Message:

Remove Input Message as it was inserted already in the SOAP Body

Desired Output Message:

<?xml version='1.0' encoding='UTF-8'?>
<S:Envelope
    xmlns:S="http://www.w3.org/2003/05/soap-envelope"
    xmlns:wsse11="http://docs.oasisopen.org/wss/oasis-wss-wssecurity-secext-1.1.xsd"
    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-wsswssecurity-utility-1.0.xsd"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:ds="http://www.w3.org/2000/09/xmldsig#"
    xmlns:saml="urn:oasis:names:tc:SAML:1.0:assertion"
    xmlns:exc14n="http://www.w3.org/2001/10/xml-exc-c14n#">
    <S:Header>
        <To mustUnderstand="true"
            xmlns="http://www.w3.org/2005/08/addressing">https://localhost:443/Gateway/PatientDiscovery/1_0/NwHINService/NwHINPatientDiscovery 
        </To>
        <Action mustUnderstand="true"
            xmlns="http://www.w3.org/2005/08/addressing">urn:hl7-org:v3:PRPA_IN201305UV02:CrossGatewayPatientDiscovery
        </Action>
        <ReplyTo mustUnderstand="true"
            xmlns="http://www.w3.org/2005/08/addressing">
            <Address>http://www.w3.org/2005/08/addressing/anonymous</Address>
        </ReplyTo>
        <MessageID mustUnderstand="true"
            xmlns="http://www.w3.org/2005/08/addressing">461433e3-4591-453b-9eb6-791c7f5ff882
        </MessageID>
        <wsse:Security S:mustUnderstand="true">
            <wsu:Timestamp wsu:Id="_1"
                xmlns:ns17="http://docs.oasis-open.org/ws-sx/wssecureconversation/200512"
                xmlns:ns16="http://schemas.xmlsoap.org/soap/envelope/">
                <wsu:Created>2012-06-08T18:31:44Z</wsu:Created>
                <wsu:Expires>2012-06-08T18:36:44Z</wsu:Expires>
            </wsu:Timestamp>
            <saml2:Assertion ID="_e1154a8a-bbd5-426d-afa5-ed7071f1b1ff" IssueInstant="2012-06-08T18:31:44.577Z" Version="2.0"
                xmlns:ds="http://www.w3.org/2000/09/xmldsig#"
                xmlns:exc14n="http://www.w3.org/2001/10/xml-excc14n#"
                xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion"
                xmlns:xenc="http://www.w3.org/2001/04/xmlenc#"
                xmlns:xs="http://www.w3.org/2001/XMLSchema">
                <saml2:Issuer Format="urn:oasis:names:tc:SAML:1.1:nameid-format:X509SubjectName">CN=SAML User,OU=SU,O=SAML User,L=Los Angeles,ST=CA,C=US</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-excc14n#"/>
                        <ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsasha1"/>
                        <ds:Reference URI="#_e1154a8a-bbd5-426d-afa5-ed7071f1b1ff">
                            <ds:Transforms>
                                <ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
                                <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-excc14n#"/>
                            </ds:Transforms>
                            <ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
                            <ds:DigestValue>5MearYAjQTErf01u/7UlKo2hEyc=</ds:DigestValue>
                        </ds:Reference>
                    </ds:SignedInfo>
                    <ds:SignatureValue>eCEFcl9iEl6u0MrAehJdsRrgbOCnirOE8i9IQpYMb25sMEaeLzXR7SFGf+TrPyv87YwYUr8lP1xK
Iohggt9yCkdvsVIOhRxiOQmK36ATjIsCNVdjqQwH2Ez9q9esRPgWIlS0vDRKxylaz1eGEX5ZCGdg
rBuScX3uvVjA5s/SVfQh6Enw9cbW/1i5Vcrvrie9ro2EdNS6CM1qLmf9bY37E5XK3f3Zt2xne1TH
OXyqH9jXU5RdE14vD+jNHAjCLq61rG5+ImWtZ2sYmp8+vLJGOVSH6yUEDV2v04AdsXUYbjgRvMjo
/mC8Mec2LdX0pGAuqS+hF4xdlR4RNI74Jj7Esg==</ds:SignatureValue>
                    <ds:KeyInfo>
                        <ds:KeyValue>
                            <ds:RSAKeyValue>
                                <ds:Modulus>maFp5lsEHjhrQQCL0e8cbxMoDpGk1r6Uion/LA2iuD3T+sspJh8TNToQrurpFFVY/u6IzHKIk64s
9894pxbwYNwv/LzRVzM5pOXmCT73KGAg3Cry+QOO5KrN8hR/OXyH90/LIS77FZY+bepqD6qx4URa
2/GLll08fu8xh1wPFDMCFAmb2Xz/5gK0fimUXJAWi1+PlNKMLnDGxHgvz5ZwiN1/QwXcQEc1mcJC
imLoiCSrk7nvmqkxX4ZZ1dYzQJWdlB8Om4r9Uu96q5cZFTYwSdivLpPFKSzn/2MI9NryZC0VaIBu
HRhgAmspAzM90BjLO5vtiwrrfx/E3uYcMjcSEQ==</ds:Modulus>
                                <ds:Exponent>AQAB</ds:Exponent>
                            </ds:RSAKeyValue>
                        </ds:KeyValue>
                    </ds:KeyInfo>
                </ds:Signature>
                <saml2:Subject>
                    <saml2:NameID Format="urn:oasis:names:tc:SAML:1.1:nameidformat:X509SubjectName">UID=WilmaAnderson</saml2:NameID>
                    <saml2:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:holder-ofkey">
                        <saml2:SubjectConfirmationData>
                            <ds:KeyInfo>
                                <ds:KeyValue>
                                    <ds:RSAKeyValue>
                                        <ds:Modulus>maFp5lsEHjhrQQCL0e8cbxMoDpGk1r6Uion/LA2iuD3T+sspJh8TNToQrurpFFVY/u6IzHKIk64s9894pxbwYNwv/LzRVz
M5pOXmCT73KGAg3Cry+QOO5KrN8hR/OXyH90/LIS77FZY+bepqD6qx4URa2/GLll08fu8xh1wPFDMCFAmb2Xz/5gK0fimUXJAWi1+PlNKML
nDGxHgvz5ZwiN1/QwXcQEc1mcJCimLoiCSrk7nvmqkxX4ZZ1dYzQJWdlB8Om4r9Uu96q5cZFTYwSdivLpPFKSzn/2MI9NryZC0VaIBuHRhg
AmspAzM90BjLO5vtiwrrfx/E3uYcMjcSEQ==</ds:Modulus>
                                        <ds:Exponent>AQAB</ds:Exponent>
                                    </ds:RSAKeyValue>
                                </ds:KeyValue>
                            </ds:KeyInfo>
                        </saml2:SubjectConfirmationData>
                    </saml2:SubjectConfirmation>
                </saml2:Subject>
                <saml2:AuthnStatement AuthnInstant="2012-06-08T18:31:44.577Z" SessionIndex="123456">
                    <saml2:AuthnContext>
                        <saml2:AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:X509</saml2:AuthnContextClassRef>
                    </saml2:AuthnContext>
                </saml2:AuthnStatement>
                <saml2:AttributeStatement>
                    <saml2:Attribute Name="urn:oasis:names:tc:xspa:1.0:subject:subject-id">
                        <saml2:AttributeValue ns6:type="ns7:string"
                            xmlns:ns6="http://www.w3.org/2001/XMLSchemainstance"
                            xmlns:ns7="http://www.w3.org/2001/XMLSchema">WilmaWA Anderson
                        </saml2:AttributeValue>
                    </saml2:Attribute>
                    <saml2:Attribute Name="urn:oasis:names:tc:xspa:1.0:subject:organization">
                        <saml2:AttributeValue ns6:type="ns7:string"
                            xmlns:ns6="http://www.w3.org/2001/XMLSchemainstance"
                            xmlns:ns7="http://www.w3.org/2001/XMLSchema">2.16.840.1.113883.3.609.10.330.000
                        </saml2:AttributeValue>
                    </saml2:Attribute>
                    <saml2:Attribute Name="urn:oasis:names:tc:xspa:1.0:subject:organization-id">
                        <saml2:AttributeValue ns6:type="ns7:string"
                            xmlns:ns6="http://www.w3.org/2001/XMLSchemainstance"
                            xmlns:ns7="http://www.w3.org/2001/XMLSchema">2.16.840.1.113883.3.609.10.330.000
                        </saml2:AttributeValue>
                    </saml2:Attribute>
                    <saml2:Attribute Name="urn:NwHIN:names:saml:homeCommunityId">
                        <saml2:AttributeValue ns6:type="ns7:string"
                            xmlns:ns6="http://www.w3.org/2001/XMLSchemainstance"
                            xmlns:ns7="http://www.w3.org/2001/XMLSchema">2.16.840.1.113883.3.609.10.330.000
                        </saml2:AttributeValue>
                    </saml2:Attribute>
                    <saml2:Attribute Name="urn:oasis:names:tc:xacml:2.0:subject:role">
                        <saml2:AttributeValue>
                            <hl7:Role code="46255001" codeSystem="2.16.840.1.113883.6.96"
codeSystemName="SNOMED_CT" displayName="Pharmacist" xsi:type="hl7:CE"
                                xmlns:hl7="urn:hl7-org:v3"
                                xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>
                            </saml2:AttributeValue>
                        </saml2:Attribute>
                        <saml2:Attribute Name="urn:oasis:names:tc:xspa:1.0:subject:purposeofuse">
                            <saml2:AttributeValue>
                                <hl7:PurposeOfUse code="OPERATIONS" codeSystem="2.16.840.1.113883.3.18.7.1" codeSystemName="NwHIN-purpose" displayName="Healthcare Operations" xsi:type="hl7:CE"
                                    xmlns:hl7="urn:hl7-org:v3"
                                    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>
                                </saml2:AttributeValue>
                            </saml2:Attribute>
                            <saml2:Attribute Name="urn:oasis:names:tc:xacml:2.0:resource:resource-id">
                                <saml2:AttributeValue ns6:type="ns7:string"
                                    xmlns:ns6="http://www.w3.org/2001/XMLSchemainstance"
                                    xmlns:ns7="http://www.w3.org/2001/XMLSchema">PATAA000000040^^^&amp;2.16.840.1.113883.3.609.20.330.000&amp;ISO
                                </saml2:AttributeValue>
                            </saml2:Attribute>
                        </saml2:AttributeStatement>
                    </saml2:Assertion>
                    <ds:Signature Id="_2"
                        xmlns:ns17="http://docs.oasis-open.org/ws-sx/wssecureconversation/200512"
                        xmlns:ns16="http://schemas.xmlsoap.org/soap/envelope/">
                        <ds:SignedInfo>
                            <ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#">
                                <exc14n:InclusiveNamespaces PrefixList="wsse S"/>
                            </ds:CanonicalizationMethod>
                            <ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
                            <ds:Reference URI="#_1">
                                <ds:Transforms>
                                    <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#">
                                        <exc14n:InclusiveNamespaces PrefixList="wsu wsse S"/>
                    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

try following :

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography.Xml;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace Certificate
{
    class Program
    {
        const string FILENAME = @"c:empest.xml";
        static void Main(string[] args)
        {
            XmlDocument doc = new XmlDocument();
            CreateSoap(doc);
            XmlElement assertion = (XmlElement)(doc.GetElementsByTagName("saml2:Assertion")[0]);
            XmlElement security = (XmlElement)(doc.GetElementsByTagName("wsse:Security")[0]);  //added 10-20-17
            XmlElement body = (XmlElement)(doc.GetElementsByTagName("soap:Body")[0]);


            using (WebClient client = new WebClient())
            {
                byte[] xmlBytes = client.DownloadData(FILENAME);
                body.InnerXml = Encoding.UTF8.GetString(xmlBytes);
            }
            string pfxpath = @"D:CertificatePrivate-cert.pfx";
            X509Certificate2 cert = new X509Certificate2(File.ReadAllBytes(pfxpath), "123456789");


            SignXmlWithCertificate(assertion, cert);
            SignXmlWithCertificate(security, cert);   //added 10-20-17

            XmlElement subject = doc.CreateElement("Subject", "saml2");
            assertion.AppendChild(subject);

            CreateSubject(subject);

            File.WriteAllText(@"D:Certificatedigitallysigned.xml", doc.OuterXml);
        }
        public static void CreateSoap(XmlDocument doc)
        {
            DateTime date = DateTime.Now;
            string soap = string.Format(
                "<?xml version="1.0"?>" +
                "<soap:Envelope" +
                " xmlns:soap="http://www.w3.org/2003/05/soap-envelope"" +
                " xmlns:wsse11="http://docs.oasisopen.org/wss/oasis-wss-wssecurity-secext-1.1.xsd"" +
                " 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-wsswssecurity-utility-1.0.xsd"" +
                " xmlns:xs="http://www.w3.org/2001/XMLSchema"" +
                " xmlns:ds="http://www.w3.org/2000/09/xmldsig#"" +
                " xmlns:saml="urn:oasis:names:tc:SAML:1.0:assertion"" +
                " xmlns:exc14n="http://www.w3.org/2001/10/xml-exc-c14n#">" +

                           "<soap:Header>" +
                                  "<To mustUnderstand="true"" +
                                     " xmlns="http://www.w3.org/2005/08/addressing">https://localhost:443/Gateway/PatientDiscovery/1_0/NwHINService/NwHINPatientDiscovery" +
                                  "</To>" +
                                  "<Action mustUnderstand="true"" +
                                     " xmlns="http://www.w3.org/2005/08/addressing">urn:hl7-org:v3:PRPA_IN201305UV02:CrossGatewayPatientDiscovery" +
                                  "</Action>" +
                                  "<ReplyTo mustUnderstand="true"" +
                                     " xmlns="http://www.w3.org/2005/08/addressing">" +
                                     "<Address>http://www.w3.org/2005/08/addressing/anonymous</Address>" +
                                  "</ReplyTo>" +
                                  "<MessageID mustUnderstand="true"" +
                                     " xmlns="http://www.w3.org/2005/08/addressing">461433e3-4591-453b-9eb6-791c7f5ff882" +
                                  "</MessageID>" +
                                  "<wsse:Security soap:mustUnderstand="true">" +
                                     "<wsu:Timestamp wsu:Id="_1"" +
                                        " xmlns:ns17="http://docs.oasis-open.org/ws-sx/wssecureconversation/200512"" +
                                        " xmlns:ns16="http://schemas.xmlsoap.org/soap/envelope/">" +
                                        "<wsu:Created>2012-06-08T18:31:44Z</wsu:Created>" +
                                        "<wsu:Expires>2012-06-08T18:36:44Z</wsu:Expires>" +
                                     "</wsu:Timestamp>" +
                                     "<saml2:Assertion ID="_883e64a747a5449b83821913a2b189e6" IssueInstant="{0}" Version="2.0"" +
                                        " xmlns:ds="http://www.w3.org/2000/09/xmldsig#"" +
                                        " xmlns:exc14n="http://www.w3.org/2001/10/xml-excc14n#"" +
                                        " xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion"" +
                                        " xmlns:xenc="http://www.w3.org/2001/04/xmlenc#"" +
                                        " xmlns:xs="http://www.w3.org/2001/XMLSchema">" +
                                        "<saml2:Issuer Format="urn:oasis:names:tc:SAML:1.1:nameid-format:X509SubjectName">CN=SAML User,OU=SU,O=SAML User,L=Los Angeles,ST=CA,C=US" +
                                        "</saml2:Issuer>" +
                                     "</saml2:Assertion>" +
                                  "</wsse:Security>" +

                                "</soap:Header>" +
                                "<soap:Body>" +
                                "</soap:Body>" +
                             "</soap:Envelope>",
                             date.ToUniversalTime().ToString("yyyy-MM-ddThh:mm:ss.fffZ"));
            //date format
            //2015-03-09T21:12:02.279Z
            doc.LoadXml(soap);

        }
        public static void SignXmlWithCertificate(XmlElement assertion, X509Certificate2 cert)
        {
            SignedXml signedXml = new SignedXml(assertion);
            signedXml.SigningKey = cert.PrivateKey;
            Reference reference = new Reference();
            reference.Uri = "";
            reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
            signedXml.AddReference(reference);

            KeyInfo keyInfo = new KeyInfo();
            keyInfo.AddClause(new KeyInfoX509Data(cert));

            signedXml.KeyInfo = keyInfo;
            signedXml.ComputeSignature();
            XmlElement xmlsig = signedXml.GetXml();

            assertion.AppendChild(xmlsig);
        }
        public static void CreateSubject(XmlElement xSubject)
        {
            string subject = "<saml2:NameID Format="urn:oasis:names:tc:SAML:1.1:nameidformat:X509SubjectName">UID=WilmaAnderson</saml2:NameID>" +
                              "<saml2:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:holder-ofkey">" +
                                "<saml2:SubjectConfirmationData>" +
                                  "<ds:KeyInfo>" +
                                    "<ds:KeyValue>" +
                                      "<ds:RSAKeyValue>" +
                                        "<ds:Modulus>" +
                                          "maFp5lsEHjhrQQCL0e8cbxMoDpGk1r6Uion/LA2iuD3T+sspJh8TNToQrurpFFVY/u6IzHKIk64s9894pxbwYNwv/LzRVz" +
                                          "M5pOXmCT73KGAg3Cry+QOO5KrN8hR/OXyH90/LIS77FZY+bepqD6qx4URa2/GLll08fu8xh1wPFDMCFAmb2Xz/5gK0fimUXJAWi1+PlNKML" +
                                          "nDGxHgvz5ZwiN1/QwXcQEc1mcJCimLoiCSrk7nvmqkxX4ZZ1dYzQJWdlB8Om4r9Uu96q5cZFTYwSdivLpPFKSzn/2MI9NryZC0VaIBuHRhg" +
                                          "AmspAzM90BjLO5vtiwrrfx/E3uYcMjcSEQ==" +
                                        "</ds:Modulus>" +
                                        "<ds:Exponent>AQAB</ds:Exponent>" +
                                      "</ds:RSAKeyValue>" +
                                    "</ds:KeyValue>" +
                                  "</ds:KeyInfo>" +
                                "</saml2:SubjectConfirmationData>" +
                              "</saml2:SubjectConfirmation>";

            xSubject.InnerXml = subject;
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...