无法将WS-Security标头添加到根据Web参考构建的请求中

时间:2019-06-12 15:04:12

标签: c# ws-security soapheader

我已经使用了WebReference,并且接收服务器需要WS-Security标头:

<wsse:UsernameToken wsu:Id="Example"> 
    <wsse:Username> ... </wsse:Username>
    <wsse:Password Type="..."> ... </wsse:Password>
    <wsse:Nonce EncodingType="..."> ... </wsse:Nonce>
    <wsu:Created> ... </wsu:Created>
</wsse:UsernameToken>

我假设它将被包含在WSDL中,但是在阅读this post之后,我知道应该分开逻辑。

我用来执行请求的客户端类包含一个代理属性IWebProxy:HttpWebClientProtocol。我相信这是我应该提供标题/覆盖信息的地方。请有人确认吗?

我还有一些我知道会生成正确标头的代码。但是,我不确定如何在不修改WebReference的情况下指定这些标头/元素。

public static Tuple<EndpointAddress, BindingElementCollection, string, string> PrepareGlowsAuth(string endpoint)
{
    EndpointAddress soapEndpoint = new EndpointAddress(string.Format("{0}/{1}", (IsProduction ? productionBaseUrl : testingBaseUrl), endpoint));
    BasicHttpsBinding binding = new BasicHttpsBinding();
    binding.Security.Mode = BasicHttpsSecurityMode.TransportWithMessageCredential;
    binding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;

    BindingElementCollection elements = binding.CreateBindingElements();
    elements.Find<SecurityBindingElement>().EnableUnsecuredResponse = true;

    return new Tuple<EndpointAddress, BindingElementCollection, string, string>(soapEndpoint, elements, "username", "password");
}

如果有人能指出我正确的方向,将不胜感激!

更新:遵循建议后,我看不到客户端或响应类。

Image to show the classes arent defined

1 个答案:

答案 0 :(得分:1)

将凭据注入请求而不更改客户端类的方式如下:

// Assume that you named your "Connected Service" com.example.foo

foo.bar requestObj= new foo.bar();

// Fill in your request object
bar.FirstName = "Someone";
// etc.

// Set up the authentication using the function you provided
var glowsAuthData = PrepareGlowsAuth("expressRateBook");

// foo.<object name>Client is automatically created, this is the generated
//   proxy class for communicating with the intended web service
foo.barClient client = new foo.barClient(new CustomBinding(glowsAuthData.Item2)
                                         , glowsAuthData.Item1);
client.ClientCredentials.UserName.UserName = glowsAuthData.Item3;
client.ClientCredentials.UserName.Password = glowsAuthData.Item4;

// Use the client to send the request object and populate the response object
// foo.<object name>Response is automatically generated when VS generates 
//   the code for "Connected Service". It also makes it the return type 
//   for foo.barClient.barResponse(foo.bar);
foo.barResponse responseObj = client.barResponse(requestObj);

假设没有异常,responseObj将包含来自服务器的响应。无需直接修改使用WSDL创建的生成的客户端。