簡體   English   中英

用於添加soap標頭的C#代碼wsse:Security,wsse:BinarySecurityToken,ds:Signature,wsse:UsernameToken,wsu:Timestamp

[英]C# code to add soap header wsse:Security, wsse:BinarySecurityToken,ds:Signature, wsse:UsernameToken,wsu:Timestamp

我們可以通過添加密鑰存儲,傳出WS-Security配置(TimeStamp,用戶名和簽名)以及usertoken,timestamp正文的命名空間從SOAP UI工具調用Web服務,然后應用傳出的wss - > apply“TimeStamp_Signed”。

但是如何在c#代碼中執行這些操作(我們正在使用java web服務)Soap Header: 在此輸入圖像描述

在此輸入圖像描述 我們使用自定義綁定選項來創建這些soap標頭,但是當我們在IClientMessageInspector中檢查時 - >還沒有創建BeforeSendRequest標頭。

此處附帶的示例代碼public static bool AcceptAllCertificatePolicy(object sender,X509Certificate certificate,X509Chain chain,SslPolicyErrors sslPolicyErrors){return true; }

    private static Binding GetCustomBinding()
    {
        var asbe = new AsymmetricSecurityBindingElement
        {
            MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12,
            InitiatorTokenParameters = new X509SecurityTokenParameters { InclusionMode = SecurityTokenInclusionMode.Never },
            RecipientTokenParameters = new X509SecurityTokenParameters { InclusionMode = SecurityTokenInclusionMode.Never },
            MessageProtectionOrder = System.ServiceModel.Security.MessageProtectionOrder.SignBeforeEncrypt,
            SecurityHeaderLayout = SecurityHeaderLayout.Strict,
            EnableUnsecuredResponse = true,
            IncludeTimestamp = true
        };

        asbe.SetKeyDerivation(false);
        asbe.AllowSerializedSigningTokenOnReply = true;

        asbe.DefaultAlgorithmSuite = System.ServiceModel.Security.SecurityAlgorithmSuite.Basic128Rsa15;
        asbe.EndpointSupportingTokenParameters.Signed.Add(new UserNameSecurityTokenParameters());
        asbe.EndpointSupportingTokenParameters.Signed.Add(new X509SecurityTokenParameters());

        var myBinding = new CustomBinding();

        myBinding.Elements.Add(asbe);

        myBinding.Elements.Add(new TextMessageEncodingBindingElement(MessageVersion.Soap11, Encoding.UTF8));

        var httpsBindingElement = new HttpsTransportBindingElement
        {
            RequireClientCertificate = true
        };

        myBinding.Elements.Add(httpsBindingElement);

        return myBinding;

    }

    private static Client GetCredentialingClient()
    {
        var customBinding = GetCustomBinding();

        var client = new Client
            (customBinding,
            new EndpointAddress(new Uri(_endpointAddress),
            new DnsEndpointIdentity(_dnsEndpointIdentity),
            new AddressHeaderCollection()));


        client.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode =
            System.ServiceModel.Security.X509CertificateValidationMode.None;

        client.Endpoint.Contract.ProtectionLevel = ProtectionLevel.Sign;
        client.Endpoint.Behaviors.Add(new InspectorBehavior());


        SetClientCredentialsSecurity(client.ClientCredentials);

        Binding binding = client.Endpoint.Binding;
        BindingElementCollection elements = binding.CreateBindingElements();
        SecurityBindingElement security = elements.Find<SecurityBindingElement>();

        if (security != null)
        {
            X509SecurityTokenParameters tokenParameters = new X509SecurityTokenParameters();
            tokenParameters.InclusionMode = SecurityTokenInclusionMode.AlwaysToRecipient;
            tokenParameters.RequireDerivedKeys = false;
            security.EndpointSupportingTokenParameters.SignedEncrypted.Add(tokenParameters);
            client.Endpoint.Binding = new CustomBinding(elements.ToArray());
        }


            return client;
    }

    private static void SetClientCredentialsSecurity(ClientCredentials clientCredentials)
    {
        clientCredentials.ServiceCertificate.Authentication.CertificateValidationMode =
               System.ServiceModel.Security.X509CertificateValidationMode.None;
        clientCredentials.UserName.UserName = _userName;
        clientCredentials.UserName.Password = _password;
        clientCredentials.ServiceCertificate.DefaultCertificate = new X509Certificate2(_certificatePath, _certificatePassword);
        clientCredentials.ClientCertificate.Certificate = new X509Certificate2(_certificatePath,_certificatePassword);
    }

    static void Main(string[] args)
    {
        ServicePointManager.ServerCertificateValidationCallback = AcceptAllCertificatePolicy;

        using (var client = GetCredentialingClient())
        {
            client.Open();



            try
            {


            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

        }

        Console.ReadLine();
    }

請幫我們在c#代碼中創建這些soap標頭

謝謝

您可以嘗試在頭節點下的xml中添加標頭。

<endpoint address="http://ws-wuxipc-5077:4000/calculator" binding="basicHttpBinding"
contract="ServiceInterface.ICalculatorService" name="cal">
<headers>
<Security xmlns="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
  <wsse:UsernameToken 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">
    <wsse:Username>
    </wsse:Username>
    <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest">monMonDePasse</wsse:Password>
    <wsse:Nonce>sdsdsdlojhfdsdM5Nw==</wsse:Nonce>
    <wsu:Created>2019-01-21T6:17:34Z</wsu:Created>
  </wsse:UsernameToken>
</Security>

或者您可以通過OperationContextScope和XmlDocument以編程方式添加標頭。

 using (ChannelFactory<ICalculatorService> ChannelFactory = new ChannelFactory<ICalculatorService>("cal"))
    {

        ICalculatorService employeeService = ChannelFactory.CreateChannel();
        using (OperationContextScope scope = new OperationContextScope((IContextChannel)employeeService))
        {

            System.Xml.XmlDocument document = new XmlDocument();


            XmlElement element = document.CreateElement("wsse", "UsernameToken", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");


            XmlElement newChild = null;

            newChild = document.CreateElement("wsse", "Username", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
            newChild.InnerText = "finance";
            element.AppendChild(newChild);

            newChild = document.CreateElement("wsse", "password", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
            newChild.SetAttribute("Type", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest");
            newChild.InnerText = "387";
            element.AppendChild(newChild);

            MessageHeader messageHeader = MessageHeader.CreateHeader("security", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", element, false);


            OperationContext.Current.OutgoingMessageHeaders.Add(messageHeader);
            employeeService.Add(5, 6);
        }


        Console.Read();
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM