title: How to make WCF Client conform to specific WS-Security - sign UsernameToken and SecurityTokenReference
body: <p>I need to create a wcf client to call a service that I have no control over. </p>
  
  <p>I have been given a wsdl and a working soapui project.</p>
  
  <p>The service uses both a username/password and a x509 certificate.</p>
  
  <hr>
  
  <p>UPDATE</p>
  
  <p>I now understand what the problem is, but am still unsure what steps I need to take to be able to create the required message, so any help would be much appreciated.</p>
  
  <p>I need to sign both the UsernameToken and the SecurityTokenReference.</p>
  
  <p>The code I had to create the custom binding has been removed from this post as its no longer used. I no longer add a SecurityBindingElement to the binding, instead I add a new behaviour that writes the security element into the header.</p>
  
  <p>So the security node is created from scratch by subclassing the SignedXml class, adding signing references and then calling ComputeSignature to create the Signature node within the Security header.</p>
  
  <p>You need to pass the xml to sign into the SignedXml constructor for this to work. It is no problem passing in the UsernameToken and this appears to be signed correctly.</p>
  
  <p>The problem is that the SecurityTokenReference is only created when ComputeSignature() is called, so I'm not able to add a signing Reference to this element, as it does not exist at the time it is required (within the overridden GetIdElement method of SignedXml which is called prior to ComputeSignature())</p>
  
  <hr>
  
  <p>The code I'm using to create the signature block to insert into the Security header is as follows</p>
  
  <pre><code>   string certificatePath = System.Windows.Forms.Application.StartupPath + "\\" + "Certs\\sign-and-    enc.p12";
  
      XmlDocument xd = new XmlDocument();
      xd.LoadXml(xml);
  
      // Set Certificate 
      System.Security.Cryptography.X509Certificates.X509Certificate2 cert = new X509Certificate2(certificatePath, "password");
      MySignedXml signedXml = new MySignedXml(xd);
      signedXml.SigningKey = cert.PrivateKey;
  
      // Create a new KeyInfo object. 
      KeyInfo keyInfo = new KeyInfo();
      keyInfo.Id = "";
  
      MemoryStream keyInfoStream = new MemoryStream();
      XmlWriter keyInfoWriter = XmlWriter.Create(keyInfoStream);
  
      WSSecurityTokenSerializer.DefaultInstance.WriteKeyIdentifierClause(keyInfoWriter, new LocalIdKeyIdentifierClause("token_reference", typeof(X509SecurityToken)));   
  
      keyInfoWriter.Flush();
      keyInfoStream.Position = 0;
      XmlDocument keyInfoDocument = new XmlDocument();
      keyInfoDocument.Load(keyInfoStream);
  
      XmlAttribute attrib = keyInfoDocument.CreateAttribute("ValueType");
      attrib.InnerText = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3";
      keyInfoDocument.ChildNodes[1].ChildNodes[0].Attributes.Append(attrib);
  
      KeyInfoNode keyInfoNode = new KeyInfoNode();
      keyInfoNode.LoadXml(keyInfoDocument.DocumentElement);
      keyInfo.AddClause(keyInfoNode);
  
      // Add the KeyInfo object to the SignedXml object. 
      signedXml.KeyInfo = keyInfo;
  
      // Need to use External Canonicalization method. 
      signedXml.SignedInfo.CanonicalizationMethod = "http://www.w3.org/2001/10/xml-exc-c14n#";
  
      // Create a reference to be signed. 
      Reference reference = new Reference();
      reference.Uri = "#UsernameToken-1";
  
      XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
      env.Algorithm = "http://www.w3.org/2001/10/xml-exc-c14n#";
      reference.AddTransform(env);
      reference.DigestMethod = "http://www.w3.org/2000/09/xmldsig#sha1";
      signedXml.AddReference(reference);
  
  
      Reference reference2 = new Reference();
      reference2.Uri = "#token_reference";
      XmlDsigEnvelopedSignatureTransform env2 = new XmlDsigEnvelopedSignatureTransform();
      env2.Algorithm = "http://www.w3.org/2001/10/xml-exc-c14n#";
      reference2.AddTransform(env2);
      reference2.DigestMethod = "http://www.w3.org/2000/09/xmldsig#sha1";
      signedXml.AddReference(reference2);
  
      // Add the Signature Id 
      signedXml.Signature.Id = "MYSIG_ID";
  
      // Compute the signature. 
      signedXml.ComputeSignature();
  
      XmlElement xmlDigitalSignature = signedXml.GetXml();
  </code></pre>
  
  <p>where the xml variable is the the UsernameToken xml string, and the MySignedXml class is a subclassed SignedXml with the GetIdElement method overridden (to try to find and correctly refreence the non-existant SecurityTokenReference)</p>
  
  <p>I've spend days researching and testing this now, and unfortunately the company supplying the service isn't any help - but I need to use their service.</p>
  
  <p><strong>Full working soap message (soapUI project)</strong></p>
  
  <pre><code>&lt;soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:XXXXX"&gt;
     &lt;soapenv:Header xmlns:ebxml="http://docs.oasis-open.org/ebxml-msg/ebms/v3.0/ns/core/200704/"&gt;
     &lt;wsse:Security soapenv:mustUnderstand="1" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"&gt;
      &lt;wsse:BinarySecurityToken EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary" ValueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3" wsu:Id="CertId-D05E596B5ABC341FEB13505090224061" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"&gt;MIIEnDCCBAWgAwIBAgIBAjANBgkqhkiG9w0BAQUFADCBxDELMAkGA1UEBhMCTloxDTALBgNVBAgTBFdHVE4xEzARBgNVBAcTCldlbGxpbmd0b24xGDAWBgNVBAoTD0lSRFN0dWR5bGlua0IyQjEUMBIGA1UECxMLRGV2ZWxvcG1lbnQxHjAcBgNVBAMTFWRldmNhLmIyYi5pcmQuZ292dC5uejEXMBUGA1UEKRMORGV2ZWxvcG1lbnQgQ0ExKDAmBgkqhkiG9w0BCQEWGWNocmlzLnNjaHVsdHpAaXJkLmdvdnQubnowHhcNMTEwOTE1MDIwNjIwWhcNMjEwOTEyMDIwNjIwWjCByTELMAkGA1UEBhMCTloxDTALBgNVBAgTBFdHVE4xEzARBgNVBAcTCldlbGxpbmd0b24xGDAWBgNVBAoTD0lSRFN0dWR5bGlua0IyQjEUMBIGA1UECxMLRGV2ZWxvcG1lbnQxJTAjBgNVBAMTHHNpZ24tYW5kLWVuYy5kZXYuaXJkLmdvdnQubnoxFTATBgNVBCkTDHNpZ24tYW5kLWVuYzEoMCYGCSqGSIb3DQEJARYZY2hyaXM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lt;ds:SignedInfo&gt;
              &lt;ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/&gt;
              &lt;ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/&gt;
              &lt;ds:Reference URI="#CertId-D05E596B5ABC341FEB13505090224061"&gt;
                  &lt;ds:Transforms&gt;
                      &lt;ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/&gt;
                  &lt;/ds:Transforms&gt;
                  &lt;ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/&gt;
                  &lt;ds:DigestValue&gt;3iVAUEAt8vAb7Ku+jf2gwSkSm0Q=&lt;/ds:DigestValue&gt;
              &lt;/ds:Reference&gt;
              &lt;ds:Reference URI="#UsernameToken-1"&gt;
                  &lt;ds:Transforms&gt;
                      &lt;ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/&gt;
                  &lt;/ds:Transforms&gt;
                  &lt;ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/&gt;
                  &lt;ds:DigestValue&gt;r4HLEAWJldJwmEmcAqV6Y8rnTPE=&lt;/ds:DigestValue&gt;
              &lt;/ds:Reference&gt;
          &lt;/ds:SignedInfo&gt;
          &lt;ds:SignatureValue&gt;
          YGh2I3VcukqjT0O7hKItiykWN5tlID18ZXRCwQjXriHmnVsO4wGcHjWfmhuNDecq+xRN+SjG8E7M
          2Rx/5/BbFKbVlNOkQOSbSxIs1YT9GaThK16pMrX5KRkkJme1W3R0pGIIQh6gGRSUf79RZUIYxyVl
          LqdIe561TXXDdtbt/6Q=
          &lt;/ds:SignatureValue&gt;
          &lt;ds:KeyInfo Id="KeyId-D05E596B5ABC341FEB13505090224372"&gt;
              &lt;wsse:SecurityTokenReference wsu:Id="STRId-D05E596B5ABC341FEB13505090224373" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"&gt;
                  &lt;wsse:Reference URI="#CertId-D05E596B5ABC341FEB13505090224061" ValueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3"/&gt;&lt;/wsse:SecurityTokenReference&gt;
          &lt;/ds:KeyInfo&gt;
      &lt;/ds:Signature&gt;
      &lt;wsse:UsernameToken wsu:Id="UsernameToken-1" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"&gt;
          &lt;wsse:Username&gt;XXXXXX&lt;/wsse:Username&gt;
          &lt;wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText"&gt;XXXXXXX&lt;/wsse:Password&gt;
          &lt;/wsse:UsernameToken&gt;
      &lt;/wsse:Security&gt;
    &lt;ebxml:Messaging xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&gt;
       &lt;ebxml:UserMessage&gt;
          &lt;ebxml:MessageInfo&gt;
             &lt;ebxml:Timestamp&gt;2002-02-02T14:18:02.0Z&lt;/ebxml:Timestamp&gt;
             &lt;ebxml:MessageId&gt;bf9433d9-c6e9-4c12-9c98-724008a09c21&lt;/ebxml:MessageId&gt;
          &lt;/ebxml:MessageInfo&gt;
          &lt;ebxml:PartyInfo&gt;
             &lt;ebxml:From&gt;
                &lt;ebxml:PartyId type="identifier"&gt;Trading Partner X&lt;/ebxml:PartyId&gt;
                &lt;ebxml:Role&gt;Provider&lt;/ebxml:Role&gt;
             &lt;/ebxml:From&gt;
             &lt;ebxml:To&gt;
                &lt;ebxml:PartyId type="identifier"&gt;XXXXXXX&lt;/ebxml:PartyId&gt;
                &lt;ebxml:Role&gt;Requestor&lt;/ebxml:Role&gt;
             &lt;/ebxml:To&gt;
          &lt;/ebxml:PartyInfo&gt;
          &lt;ebxml:CollaborationInfo&gt;
             &lt;ebxml:AgreementRef&gt;urn:XXXXXXXXX&lt;/ebxml:AgreementRef&gt;
             &lt;ebxml:Service type="Web Service"&gt;urn:XXXXXXXX&lt;/ebxml:Service&gt;
             &lt;ebxml:Action&gt;customerInformation&lt;/ebxml:Action&gt;
             &lt;ebxml:ConversationId&gt;e302426a-b2d9-4ff1-a14b-fbbc2f40a017&lt;/ebxml:ConversationId&gt;
          &lt;/ebxml:CollaborationInfo&gt;
       &lt;/ebxml:UserMessage&gt;
    &lt;/ebxml:Messaging&gt;
     &lt;/soapenv:Header&gt;
     &lt;soapenv:Body&gt;
    &lt;urn:ConnectionTest&gt;
       &lt;Message&gt;Bonjour&lt;/Message&gt;
    &lt;/urn:ConnectionTest&gt;
     &lt;/soapenv:Body&gt;
  &lt;/soapenv:Envelope&gt;
  </code></pre>
  
  <p>We were supplied with some documentation. The security section is copied below</p>
  
  <p>The following security must be applied to each request in the following order:
  A wsse:UsernameToken must be included and contain:</p>
  
  <ol>
  <li>The Agent‟s Portal Username for the value of the wsse:Username element</li>
  <li><p>The Agent‟s Portal Password for the value of the wsse:PasswordText (clear text) in the Password element
  A Signature block:
  Digital Signatures are created using x509 certificates. Each software provider is required to hold and protect a valid certificate and private key issued by [To Be Determined]. With each service request the software must:</p></li>
  <li><p>Include the Certificate that matches the private key used for signing as a wsse:BinarySecurityToken and use it as the wsse:SecurityTokenReference for the Signature</p></li>
  <li>Sign the wsse:BinarySecurityToken</li>
  <li>Sign the wsse:UsernameToken</li>
  <li>Use Canonicalization Method Algorithm: <a href="http://www.w3.org/2001/10/xml-exc-c14n#" rel="noreferrer">http://www.w3.org/2001/10/xml-exc-c14n#</a></li>
  <li>Use Signature Method Algorithm: <a href="http://www.w3.org/2000/09/xmldsig#rsa-sha1" rel="noreferrer">http://www.w3.org/2000/09/xmldsig#rsa-sha1</a></li>
  <li>Use Digest Method Algorithm: <a href="http://www.w3.org/2000/09/xmldsig#sha1" rel="noreferrer">http://www.w3.org/2000/09/xmldsig#sha1</a>  </li>
  </ol>
  
  <h2><strong>Update</strong></h2>
  
  <p>Image of the SoapUI configuration I was initially given
  <a href="https://i.stack.imgur.com/35OHA.png" rel="noreferrer"><img src="https://i.stack.imgur.com/35OHA.png" alt="SoapUIConfig"></a></p>