C# CXF web服务的.NET客户端身份验证和SOAP凭据头

C# CXF web服务的.NET客户端身份验证和SOAP凭据头,c#,web-services,authentication,cxf,soapheader,C#,Web Services,Authentication,Cxf,Soapheader,场景 我必须使用.NET客户端访问web服务。 该服务是一个apachecxfweb服务。 需要用户名和密码身份验证。 我已经创建了代理。 我已设置凭据 MyServiceReference proxy = new MyServiceReference(); proxy.Credentials = new NetworkCredential("username", "password"); string res = proxy.Method1(); 运行客户端时,会引发以下异常: System

场景

我必须使用.NET客户端访问web服务。 该服务是一个apachecxfweb服务。 需要用户名和密码身份验证。 我已经创建了代理。 我已设置凭据

MyServiceReference proxy = new MyServiceReference();
proxy.Credentials = new NetworkCredential("username", "password");
string res = proxy.Method1();
运行客户端时,会引发以下异常:

System.Web.Services.Protocols.SoapHeaderException: An error was discovered processing the <wsse:Security> header
System.Web.Services.Protocols.SoapHeaderException:处理标头时发现错误
服务发布者告诉我,SOAP头中不存在凭据。 所以,我想这不是设置身份验证的正确方法

问题


那么,如何设置身份验证所需的SOAP头呢?

最终,我不得不调用服务,创建整个SOAP消息并发出
HttpWebRequest
。在SOAP消息中,我手动指定安全标头:

<soapenv:Header>
  <wsse:Security soapenv:mustUnderstand='1' xmlns:wsse='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd'>
     <wsse:UsernameToken wsu:Id='UsernameToken-1' xmlns:wsu='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd'>
        <wsse:Username>Foo</wsse:Username>
        <wsse:Password Type='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText'>Bar</wsse:Password>
        <wsse:Nonce EncodingType='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary'>qM6iT8jkQalTDfg/TwBUmA==</wsse:Nonce>
        <wsu:Created>2012-06-28T15:49:09.497Z</wsu:Created>
     </wsse:UsernameToken>
  </wsse:Security>
</soapenv:Header>
有关Web服务安全性(WSS)的有趣资源:

String Uri = "http://web.service.end.point"
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(Uri);
req.Headers.Add("SOAPAction", "\"http://tempuri.org/Register\"");
req.ContentType = "text/xml;charset=\"utf-8\"";
req.Accept = "text/xml";
req.Method = "POST";

String SoapMessage = "MySoapMessage, including envelope, header and body"
using (Stream stm = req.GetRequestStream())
{
    using (StreamWriter stmw = new StreamWriter(stm))
    {
        stmw.Write(SoapMessage);
    }
}


try
{
    WebResponse response = req.GetResponse();
    StreamReader sr = new StreamReader(response.GetResponseStream());
    log.InfoFormat("SoapResponse: {0}", sr.ReadToEnd());
}
catch(Exception ex)
{
    log.Error(Ex.ToString());
}