Добавить заголовок безопасности к сообщению SOAP - PullRequest
0 голосов
/ 19 марта 2020

Я не очень опытен в soap звонках. Я должен сделать следующий soap звонок. Я страдал с этим в течение нескольких дней, но он не работает.

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:v1="http://eeszt.gov.hu/ns/helloworld/ws/HelloWorldService/v1">
<soapenv:Header>
  <wsse:Security soapenv:mustUnderstand="1" xmlns:wsse="http://docs.oasisopen.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-wssecurityutility-1.0.xsd">
     <wsu:Timestamp wsu:Id="TS-B05DFFAAB2CD6C6C9E14363584263357">
     <wsu:Created>2015-07-08T12:27:06.335Z</wsu:Created>
     <wsu:Expires>2015-07-08T12:32:06.335Z</wsu:Expires>
     </wsu:Timestamp>
      <saml:Assertion ID="id-" ...</saml:Assertion>
   </wsse:Security>
</soapenv:Header>
<soapenv:Body>
  <v1:helloWorldRequest>
  ...
  </v1:helloWorldRequest>
</soapenv:Body>
</soapenv:Envelope

Это то, что я пытался

  1. Создание пользовательских привязок и веб-службы
CustomBinding wsBinding = new CustomBinding();
string baseAddress = "https://dev-if.eeszt.gov.hu:443/TOR";
EndpointAddress wsEndPointAddress = new EndpointAddress(new Uri(baseAddress));
wsBinding = CreateBindingForTp();
TorWSClient twsClient = new TorWSClient(wsBinding, wsEndPointAddress);

X509Certificate2 x509 = new X509Certificate2(@eesztCert.certFileName, @eesztCert.certPassword, X509KeyStorageFlags.MachineKeySet);
byte[] rawData = ReadFile(@eesztCert.certFileName);
x509.Import(rawData, @eesztCert.certPassword, X509KeyStorageFlags.MachineKeySet);
twsClient.ClientCredentials.ClientCertificate.Certificate = x509;

twsClient.Open();
Добавить заголовок безопасности и вызвать веб-сервис
 SoapSecurityHeader soapSecurityHeader = new SoapSecurityHeader(Saml.samlTicket);
 using (OperationContextScope scope = new OperationContextScope((IContextChannel)twsClient.InnerChannel))
   {
      OperationContext.Current.OutgoingMessageHeaders.Add(soapSecurityHeader);
   }

try
 {
   gtrspt = twsClient.getTorzs(gtrt);
 }
catch (Exception ex)
 {
    MessageBoxEx.Show(ex.Message, "Error !", MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);
 }
Создать заголовок безопасности
 public class SoapSecurityHeader : MessageHeader
    {
        private readonly string  _samlticket;
        private readonly DateTime _createdDate;

        public SoapSecurityHeader(string samlTicket)
        {
            _samlticket = samlTicket;
            _createdDate = DateTime.Now;
        }

        public string Id { get; set; }


        public override string Name
        {
            get { return "Security "; }
        }

        public override string Namespace
        {
            get { return "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"; }
        }

        protected override void OnWriteStartHeader(XmlDictionaryWriter writer, MessageVersion messageVersion)
        {
            writer.WriteStartElement("wsse", Name, Namespace);
            writer.WriteXmlnsAttribute("wsu", "wsu http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
        }

        protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion)
        {
            writer.WriteStartElement("wsu", "Timestamp", null);
            writer.WriteAttributeString("wsu", "Id", null, "TimeId1");
            writer.WriteElementString("wsu", "Created", null, _createdDate.ToUniversalTime().ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'"));
            writer.WriteElementString("wsu", "Expires", null, _createdDate.AddSeconds(300).ToUniversalTime().ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'"));

            writer.WriteEndElement();

            string sml = Saml.samlTicket;
            writer.WriteRaw("<saml:Assertion ID=" + @"""");
            writer.WriteRaw(sml + @"""");
            writer.WriteRaw("</saml:Assertion>");

        }
    }
}
Binding
public CustomBinding CreateBindingForTp()
        {

            CustomBinding customBinding = new CustomBinding();
            TransportSecurityBindingElement security = new TransportSecurityBindingElement()
            {
                IncludeTimestamp = true,
                MessageSecurityVersion = MessageSecurityVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10
            };

            TextMessageEncodingBindingElement encoding = new TextMessageEncodingBindingElement(MessageVersion.Soap11, Encoding.UTF8);
            HttpsTransportBindingElement transport = new HttpsTransportBindingElement() { TransferMode = TransferMode.Buffered, RequireClientCertificate = true, MaxReceivedMessageSize = Int32.MaxValue };

            customBinding.Elements.Clear();
            customBinding.Elements.Add(security);
            customBinding.Elements.Add(encoding);
            customBinding.Elements.Add(transport);

            return customBinding;
        }

Я сгенерировал прокси-класс из wsdl. Должен быть добавлен только один заголовок wsse. Заголовок wsse не включен в вызов веб-службы.

Я хочу более простое решение. Извините за мой плохой Энгли sh. Спасибо за помощь.

...