使用基本验证和客户端证书调用WCF服务



我们将客户端写入使用CSR证书和基本身份验证的WCF服务。

我们的C#客户端是通过Visual Studio生成的,我们可以通过编程方式设置证书和用户名/密码。但是,我们必须手动发送基本验证标题,否则我们会收到错误:

'The HTTP request is unauthorized with client authentication scheme 'Anonymous'. The authentication header received from the server was 'Basic realm="HttpBasicAuthentication"'.'

我们的代码是:

var myBinding = new WSHttpBinding();
myBinding.Security.Mode = SecurityMode.Transport;
myBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;
myBinding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;
var ea = new EndpointAddress("https://example.org/myservice");
var client = new MandateWebServiceClient(myBinding, ea);
client.ClientCredentials.UserName.UserName = "wally";
client.ClientCredentials.UserName.Password = "walliesWorld";
client.ClientCredentials.ClientCertificate.Certificate = new X509Certificate2("C:\some\path\to\csr.pfx", "password");
using (var scope = new OperationContextScope(client.InnerChannel))
{
    var httpRequestProperty = new HttpRequestMessageProperty();
    httpRequestProperty.Headers[HttpRequestHeader.Authorization] =
        "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(client.ClientCredentials.UserName.UserName + ":" + client.ClientCredentials.UserName.Password));
    OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty;
    client.create();
}

使用上述代码,我们可以成功与服务交谈。如果我们删除了using块中的行,则身份验证方案将更改为Anonymous,并在上面获得错误。

上面的安排似乎有点蜂蜜。我们尝试了所有可能的SecurityMode设置,而使用HttpClientCredentialType.CertificateSecurityMode.Transport是允许接受证书的唯一组合。设置或不设置MessageCredentialType.UserName似乎对系统没有影响。

是否有任何.NET框架提供证书和基本身份验证标头的方式,而不是手动添加标头?

服务器如何同时使用证书身份验证和基本身份验证?这似乎是多余的。因为可以使用证书对客户端进行身份验证(签发证书并建立服务器与客户端之间的关系(是安全的,所以我们为什么需要通过基本身份验证对客户端进行身份验证?因此,您确定客户需要提供证书吗?我认为,服务器可能已经使用了运输安全模式,并设置了基本的身份验证,因此客户可能不需要提供证书。
这是我想的服务器端配置。
服务器。

Uri uri = new Uri("https://localhost:9900");
        WSHttpBinding binding = new WSHttpBinding();
        binding.Security.Mode = SecurityMode.Transport;
        binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;

客户端(通过添加服务参考调用,客户代理类/绑定类型是通过服务MEX端点自动生成的,https://https://localhost:9900/mex(


ServiceReference1.ServiceClient client = new ServiceReference1.ServiceClient();
            client.ClientCredentials.UserName.UserName = "administrator";
            client.ClientCredentials.UserName.Password = "abcd1234!";

基于此,我有一个问题,通过添加服务参考来调用服务时,自动生成的绑定类型是什么?
期待您的答复。

最新更新