如何在 C# 中使用第三方 https wsdl Web 服务 [英] How to consume third party https wsdl web service in c#

查看:42
本文介绍了如何在 C# 中使用第三方 https wsdl Web 服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 SoapUI 工具中,我配置了带有传出 WS-Security 配置的 .Jks 文件签名是 BinarySecurityToken,算法是 CanonicalizationMethod 和 SignatureMethod,它运行良好.

In SoapUI tool I've configured .Jks file with Outgoing WS-Security Configurations Signature is BinarySecurityToken and algorithm is CanonicalizationMethod and SignatureMethod it is working perfectly.

现在我尝试使用如下 C# 代码:

Now I try to consume from C# code as below :

SprintApiService.QueryCsaPortTypeClient client = new QueryCsaPortTypeClient();

ClientCredentials ce = new ClientCredentials();
string fileName = Server.MapPath("");
fileName = fileName + "/test-01.pfx";
ce.ClientCertificate.Certificate = new X509Certificate2(fileName, "tag123");
var val = ce.ClientCertificate.Certificate.GetSerialNumber();
ce.ClientCertificate.SetCertificate("CN=jaitest-01, OU=TPA, OU=BMP, OU=Projects, O=Sprint, C=us", StoreLocation.CurrentUser, StoreName.TrustedPeople);

System.IdentityModel.Selectors.SecurityTokenManager sTokenMgr = ce.CreateSecurityTokenManager();
//var sTokenMgr = ce.CreateSecurityTokenManager();

但我没能成功.我总是收到被客户(政策)拒绝",请帮助我.

But I could not succeed. I am always getting "Rejected by Client (Policy)" please help me.

这是在 SoapUI 工具中创建的示例请求:

This is sample request which is created in SoapUI tool :

<wsse:Security SOAP-ENV:mustUnderstand="1" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
         <wsu:Timestamp wsu:Id="Timestamp-c55ce328-af36-4b0f-97d8-3bab57ee6a46" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
            <wsu:Created>2014-02-18T12:27:52Z</wsu:Created>
            <wsu:Expires>2014-02-18T12:32:52Z</wsu:Expires>
         </wsu:Timestamp>
         <wsse:BinarySecurityToken wsu:Id="SecurityToken-1da2e6b0-3a0d-4943-bcae-de0805d9c4c5" 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" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">MIIDmTCCAwKgAwIBAgIERxqCLDANBgkqhkiG9w0BAQUFADAeMQswCQYDVQQGEwJVUzEPMA0GA1UEChMGU3ByaW50MB4XDTExMDgwMjIwMDc0OVoXDTE4MDgwNDA0MDAwMFowYjELMAkGA1UEBhMCVVMxDzANBgNVBAoTBlNwcmludDERMA8GA1UECxMIUHJvamVjdHMxDDAKBgNVBAsTA0JNUDEMMAoGA1UECxMDVFBBMRMwEQYDVQQDEwpzcHJpbnQtbXNvMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCG2yDWPQBNG9bjt+sVMzlaooX3jON7tOoqtIxPkXl7XCEvbzZpXL2tYtHXqxVfPo9h1weulbj0dE4LlVjlTjzW4upBI92StqDVYdzTLvZWie1fEslIThHDoX7paQpnrSew3TZ6fk4qVnF4h44J/rLnFt3jLEO6IyRhddganpoOowIDAQABo4IBnjCCAZowCwYDVR0PBAQDAgWgMCsGA1UdEAQkMCKADzIwMTEwODAyMjAwNzQ5WoEPMjAxODA4MDQwNDAwMDBaMBEGCWCGSAGG+EIBAQQEAwIFoDCB5AYDVR0fBIHcMIHZMDagNKAypDAwLjELMAkGA1UEBhMCVVMxDzANBgNVBAoTBlNwcmludDEOMAwGA1UEAxMFQ1JMMjkwgZ6ggZuggZiGSmxkYXA6Ly9jYXg1MDAxLnNwcmludC5jb206Mzg5L289U3ByaW50LGM9VVM/Y2VydGlmaWNhdGVSZXZvY2F0aW9uTGlzdD9iYXNlhkpsZGFwOi8vY2F4NTAwMi5zcHJpbnQuY29tOjM4OS9vPVNwcmludCxjPVVTP2NlcnRpZmljYXRlUmV2b2NhdGlvbkxpc3Q/YmFzZTAfBgNVHSMEGDAWgBRFTY2yujBdccYEb58W/Dt7VY3NHzAdBgNVHQ4EFgQUzUEoNuQ9ummaIU8K6h28izpV2YUwCQYDVR0TBAIwADAZBgkqhkiG9n0HQQAEDDAKGwRWNy4xAwIDKDANBgkqhkiG9w0BAQUFAAOBgQCTDjwpnYdx9JZpBrIwm4qIF4tZmXCCUIBEcoER1oUw/NSdgbbRjpU5AxUR/aK1K3taa27HS+WBQYTeMw+Y/LFhp8m+UjHBx/O1kfk4JAz201Kk0HeGgFvt9sscLfK8YD0aavdDJ6Z0rMpHBlcv8VQ7P+1zqJLay3TY+atl9wuD/Q==</wsse:BinarySecurityToken>
         <Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
            <SignedInfo>
               <CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
               <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
               <Reference URI="#Timestamp-c55ce328-af36-4b0f-97d8-3bab57ee6a46">
                  <Transforms>
                     <Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
                  </Transforms>
                  <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
                  <DigestValue>8H8usvOvRYPwOKHVHdOXO6Y3Cz4=</DigestValue>
               </Reference>
               <Reference URI="#Body-db900962-5b93-4a49-a70a-a1745bed8255">
                  <Transforms>
                     <Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
                  </Transforms>
                  <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
                  <DigestValue>54u/0PxaY+S7RigxrisF2Chnplc=</DigestValue>
               </Reference>
            </SignedInfo>
            <SignatureValue>HC10RHq8lweC1KLGAzw1pxjju5LbWASn5GUCxane36DqUxaXQQnBrF0fyBkpI70H+ncrYaO00sxVd1QWnLfYxzl/YEWfHus/qObmFckRnNsEnx9MV5ejHhntbXdzIc9RFbXoFGPcoEGAsKoUbeOi7UWKbofzATG6VMlKhLFz01k=</SignatureValue>
            <KeyInfo>
               <wsse:SecurityTokenReference xmlns="">
                  <wsse:Reference URI="#SecurityToken-1da2e6b0-3a0d-4943-bcae-de0805d9c4c5" ValueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3"/>
               </wsse:SecurityTokenReference>
            </KeyInfo>
         </Signature>
</wsse:Security>      

谢谢...

推荐答案

感谢上帝,经过长时间的研究,我终于找到了解决方案,谷歌搜索/搜索和努力工作.回顾一下:第三方网络服务(用 Java 编码)使用 X509 SecurityToken Https 证书消费.NET.

Thank god, finally i've found a solution after a long research, googling/binging and hard work. Just Recap: Third party web service (coded in Java) with X509 SecurityToken Https certificate consume in .NET.

是的,我们可以使用 WSE 使用旧技术来使用上述服务2.0/WSE 3.0(Web 服务增强)和最新使用 WCF.我刚刚尝试使用 WSE 2.0,它按预期工作,但出现错误代码WSE464: No policy could be found for this message"我仍然可以在 try..catch 块中看到响应并使用适当的解密 XML 响应消息.

Yes, we can consume the above service using old technology using WSE 2.0 / WSE 3.0 (Web Services Enhancements) and Latest using WCF. I've just tried using WSE 2.0 it's working as expected but with Error code "WSE464: No policy could be found for this message" still i can able to get see response in try..catch block and use appropriate decrypt XML response message.

遵循的步骤

  • 安装客户端给定的证书(.pfx)

  • Install the client given certificate (.pfx)

在运行命令类型 mmc → Enter 中打开 Microsoft 管理控制台 (MMC)一个.文件 → 添加/删除管理单元 → 在列表框中选择证书 → 单击添加 → 选择我的
当前用户 → 完成 -> 单击确定.

Open Microsoft Management Console (MMC) in run command type mmc → Enter a. File → Add/Remove snap in → Select certificate in list box → Click Add → Select My
Current User → Finish –> Click Ok.

     b. Select Trusted Root Certification → Expand it → Select Certificate → Right click on           
         Certificate → Select All Tasks → Import → Select your Certificate location and finish the  
          wizard process

  • 对本地计算机(本地计算机)重复第 2 步

  • Repeat Step 2 for Local Machine (Local Computer)

    安装 Microsoft WSE(Web 服务增强)2.0 SP3/WSE 3.0 注意.WSE 2.0/3.0 将仅支持 .Net Framework 2.0.http://www.microsoft.com/en-in/download/details.aspx?id=23689

    Install Microsoft WSE (Web Services Enhancements) 2.0 SP3 / WSE 3.0 Note. WSE 2.0/3.0 will support .Net Framework 2.0 only. http://www.microsoft.com/en-in/download/details.aspx?id=23689

    在 Visual Studio 中创建新的 Web 应用程序项目展开项目→右键单击参考→添加服务参考→高级→添加Web参考→将您的服务WSDL链接粘贴到URL文本框中→单击Go按钮(指向右箭头)→由于它是https,它将显示带有警告消息单击的弹出窗口是的,直到它停止 → 输入 Web 参考名称并单击添加参考按钮右键单击→参考→添加参考→单击浏览→Program FilesMicrosoft WSEv2.0→选择Microsoft.Web.Services2.dll"→单击添加现在生成的代理/存根类 → 如果不可见,请在 Web Reference 文件夹下查找 Reference.cs 文件,单击在解决方案资源管理器中显示所有文件.→ 打开 Reference.cs 文件并将System.Web.Services.Protocols.SoapHttpClientProtocol"替换为WebServicesClientProtocol"

    Create new web application project in Visual Studio Expand project → Right click on Reference → Add Service Reference → Advanced → Add Web Reference → Paste your Service WSDL link in URL text box → Click on Go button (Pointing right arrow) → Since it's https it will show with popup with warning message click Yes until it's stops → Enter Web Reference name and click Add Reference button Right click → Reference → Add reference → Click Browse → Program FilesMicrosoft WSEv2.0 → Select "Microsoft.Web.Services2.dll" → Click Add Proxy/Stubbed class generated now → Look for Reference.cs file under Web Reference folder if not visible click Show all files in Solution Explorer. → Open Reference.cs file and Replace "System.Web.Services.Protocols.SoapHttpClientProtocol" with "WebServicesClientProtocol"

        protected void Page_Load(object sender, EventArgs e)
        {
            private static string ClientBase64KeyId = "XPaTfx6Lx8dV/oh6ebOeOo4Xdummy";
            MyService myClient = new MyService();
            try
            {
               SecurityToken signingToken = GetClientToken(false);
               //Get the SoapContext for the SOAP request.
               SoapContext requestContext = client.RequestSoapContext;
    
               // Expire this message one minute after it is sent.
               requestContext.Security.Timestamp.TtlInSeconds = 3600;
    
                // Add the X509 certificate to the WS-Security header.
                requestContext.Security.Tokens.Add(signingToken);
    
                MessageSignature sig = new MessageSignature(signingToken);
    
                requestContext.Security.Elements.Add(sig);
    
                RequestClass request = new RequestClass();
                request.Name ="";
                ResponceClass  responce  = myClient.QueryCsa(request);
            }
            catch(Exception ex)
            {
               lblResultMessage.Text = ex.Message;
            }
    
    
        public static X509SecurityToken GetClientToken(bool selectFromList)
        {
            X509SecurityToken token = null;
    
            // Open the CurrentUser Certificate Store and try MyStore only
            X509CertificateStore store = X509CertificateStore.CurrentUserStore(X509CertificateStore.MyStore);
            if (selectFromList)
            {
                //token = RetrieveTokenFromDialog(store);
            }
            else
            {
                token = RetrieveTokenFromStore(store, ClientBase64KeyId);
            }
    
            return token;
        }
    
       private static X509SecurityToken RetrieveTokenFromStore(X509CertificateStore store, string keyIdentifier)
        {
            if (store == null)
                throw new ArgumentNullException("store");
    
            X509SecurityToken token = null;
    
            try
            {
                if (store.OpenRead())
                {
                    // Place the key ID of the certificate in a byte array
                    // This KeyID represents the Wse2Quickstart certificate included with the WSE 2.0 Quickstarts
                    // ClientBase64KeyId is defined in the ClientBase.AppBase class
                    Microsoft.Web.Services2.Security.X509.X509CertificateCollection certs = store.FindCertificateByKeyIdentifier(Convert.FromBase64String(keyIdentifier));
    
                    if (certs.Count > 0)
                    {
    
                        if (!certs[0].SupportsDigitalSignature ||
                    (certs[0].Key == null))
                        {
                            //MessageBox.Show(
                            //    "The certificate must support digital " +
                            //    "signatures and have a private key available.");
                            //securityToken = null;
                        }
                        // Get the first certificate in the collection
                        token = new X509SecurityToken(((Microsoft.Web.Services2.Security.X509.X509Certificate)certs[0]));
                    }
                }
            }
            finally
            {
                if (store != null)
                    store.Close();
            }
    
            return token;
        }
    

    }

    在您的页面中添加以下代码并从 X509 证书工具中获取 ClientBase64KeyId 值.

    Add the following code in in your page and Get ClientBase64KeyId value from X509 Certficate Tool.

    开始 → 程序文件 → Microsoft WSE 2.0 → X509 证书工具 → 选择证书位置是本地计算机 → 名称是个人 → 单击打开证书按钮,列出证书并选择使用 MMC 安装的相应证书.现在从 Key Identifier (Based64 Encoded) 值中选择值并在代码下方使用它.如果您的应用程序是 Asp.Net Web 应用程序,它可能无法访问,因此请单击查看私钥文件属性"按钮并在同一工具本身中分配适当的安全权限.

    Start → Program Files → Microsoft WSE 2.0 → X509 Certificate Tool → Select Certificate Location is Local Computer → Sore Name is Personal → Click Open Certificate Button, listed with certificates and select appropriates which is one installed using MMC. Now pick the values from Key Identifier (Based64 Encoded) value and use it below code. If your application is Asp.Net Web application, it may not accessible so click 'View Private Keys File Properties' button and assign appropriate Security permission in the same tool itself.

    我们几乎完成了 70% 的工作.现在这是非常关键的部分……是的,我们将应用策略详细信息.这都是与 X509 证书相关的安全策略,它定义了它将要签署(签名)、加密、完整性、机密性的部分等等.不要惊慌,我们有名为 WSE 2.0 Tool 的助手,是的,chumma :) 试试看开始 → 程序文件 → Microsoft WSE 2.0 → 配置编辑器 → 文件 → 打开 → 从您的应用程序指向 Web.config

    Almost we've done 70% of work. Now it's very crucial part going to do now... Yes we're going to apply Policy details.This is all about Security Policy related to X509 Certificate which defines about what part it's going to Sign (Signature), Encryption, Integrity, Confidentiality and so on. Don't panic we have helper called WSE 2.0 Tool, Yes chumma :) try it Start → Program Files → Microsoft WSE 2.0 → Configuration Editor → File → Open → Point to Web.config from your application

    常规 => 选中两个复选框

    General => Check both the Check Boxes

    安全、路由和自定义过滤器 => 他们不叫我:)所以离开它.

    Security, Routing and Customized Filters => They are not called me:) So Leave It.

    政策 => 非常重要.1.勾选启用策略 2.点击添加→名称
    它/输入任何名称→下一步→保持默认(安全客户端
    应用程序)→(默认)下一步→下一步→(默认:X509证书)→下一步 → 选择证书 → 从
    中选择适当的证书列表→确定→下一步→完成

    Policy => Very Important. 1. Check Enable Policy 2.Click Add → Name
    it / Enter any name → Next → Leave it default (Secure Client
    Application) → (Default) Next → Next → (Default: X509 Certificate) → Next → Select Certificate → Select appropriate certificate from the
    list → Ok → Next → Finish

    TokenIssuing => 放手

    TokenIssuing => Leave it

    诊断 => 选中相应的复选框以进行跟踪和
    记录目的

    Diagnostics => Check it appropriate check boxes for tracing and
    logging purpose

    文件→保存→关闭它:)

    File → Save → Close it :)

    现在可以创建在 Web.config 文件中引用的 policyCache.config.在这里,我们将 HTTPS 服务 URL 添加到 .完成

    Now one would've created policyCache.config which is referenced in Web.config file. Here we have add our HTTPS service URL in . Done

    这是由 WSE 2.0 实现的.是的,我知道这是旧技术.我是尝试将 WCF 作为客户端使用...我将在下一个会话中发布...

    :) 快乐编程 :)贾桑卡尔

    :) Happy Programming :) JaiSankar

    这篇关于如何在 C# 中使用第三方 https wsdl Web 服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆