简体   繁体   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

we are able to invoke the web service from SOAP UI tool by adding key store, Outgoing WS-Security Configuration (TimeStamp, UserName & Signature) and namespaces for usertoken, timestamp body and then apply outgoing wss -> apply "TimeStamp_Signed". 我们可以通过添加密钥存储,传出WS-Security配置(TimeStamp,用户名和签名)以及usertoken,timestamp正文的命名空间从SOAP UI工具调用Web服务,然后应用传出的wss - > apply“TimeStamp_Signed”。

But how to do these things in c# code (we are consuming java web service) Soap Header : 但是如何在c#代码中执行这些操作(我们正在使用java web服务)Soap Header: 在此输入图像描述

在此输入图像描述 We are used custom binding option to create these soap headers but when we inspect in IClientMessageInspector -> BeforeSendRequest header was not been created. 我们使用自定义绑定选项来创建这些soap标头,但是当我们在IClientMessageInspector中检查时 - >还没有创建BeforeSendRequest标头。

Sample Code attached here public static bool AcceptAllCertificatePolicy(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; 此处附带的示例代码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();
    }

Please do help us to create these soap header in c# code 请帮我们在c#代码中创建这些soap标头

Thank You 谢谢

You could try to add header in your xml under headers node. 您可以尝试在头节点下的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>

Or you could add header programmatically through OperationContextScope and XmlDocument. 或者您可以通过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.

相关问题 WSSecurityException - 发现处理错误的错误 <wsse:Security> 头 - WSSecurityException - An error was discovered processing the <wsse:Security> header javax.xml.soap.SOAPException:无法找到前缀名称空间:wsse HEADER安全性 - javax.xml.soap.SOAPException:unable to find namespace for prefix: wsse HEADER Security Web Service wsse安全实现 - Web Service wsse security implementation 如何将 wsse:KeyIdentifier 更改为 wsse:Reference with CXF - how to change wsse:KeyIdentifier to wsse:Reference with CXF WCF\\.Net\\C# 中的 WSSE(带摘要) - 一个简单的方法? - WSSE (with digest) in WCF\.Net\C# - An easy way? WSSE - 在 soapenv:Header 中签署一个元素 - WSSE - Sign an element inside soapenv:Header 使用WSS4J进行的安全Web服务调用返回“在处理 <wsse:Security> 标头” - Secure web service calls using WSS4J return “An error was discovered processing the <wsse:Security> header” 安全 Web 服务异常:此服务需要<wsse:security> ,这是缺失的</wsse:security> - Secured Web Service Exception: This service requires <wsse:Security>, which is missing 如何将SOAP安全头(UsernameToken)信息添加到代码优先的Webservice生成的WSDL中 - How to add SOAP Security Header (UsernameToken) information to code-first Webservice Generated WSDL 使用UsernameToken保护WS客户端(SOAP安全标头) - Secure WS client with UsernameToken(SOAP security header)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM