【发布时间】:2014-11-27 22:23:21
【问题描述】:
我正在尝试创建一个安全的网络服务。
这里是合约和服务实现
[ServiceContract()]
public interface ICalculatorService
{
[OperationContract()]
int Add(int x, int y);
}
[ServiceBehavior(IncludeExceptionDetailInFaults=true)]
public class CalculatorService : ICalculatorService
{
public int Add(int x, int y)
{
return x + y;
}
}
这里有服务代码
var b = new WSHttpBinding(SecurityMode.Transport);
b.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;
b.Security.Message.ClientCredentialType = MessageCredentialType.None;
Type contractType = typeof(ICalculatorService);
Type implementedContract = typeof(CalculatorService);
Uri baseAddress = new Uri("https://localhost:8006/CalculatorService");
ServiceHost sh = new ServiceHost(implementedContract);
sh.AddServiceEndpoint(contractType, b, baseAddress);
//ServiceMetadataBehavior sm = new ServiceMetadataBehavior();
//sm.HttpsGetEnabled = true;
//sm.HttpsGetUrl = new Uri("https://localhost:8006/CalculatorServiceMex");
//sh.Description.Behaviors.Add(sm);
sh.Credentials.Peer.PeerAuthentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.PeerTrust;
sh.Credentials.ServiceCertificate.SetCertificate(StoreLocation.LocalMachine, StoreName.TrustedPeople, X509FindType.FindBySubjectName, "localhost");
sh.Open();
Console.WriteLine("Service is Listening");
Console.ReadLine();
sh.Close();
这是客户端代码
var b = new WSHttpBinding(SecurityMode.Transport);
b.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;
b.Security.Message.ClientCredentialType = MessageCredentialType.None;
var factory = new ChannelFactory<ICalculatorService>(b);
factory.Credentials.Peer.PeerAuthentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.PeerTrust;
factory.Credentials.ClientCertificate.SetCertificate(StoreLocation.LocalMachine, StoreName.TrustedPeople, X509FindType.FindBySubjectName, "localhost");
var client = factory.CreateChannel(new EndpointAddress(new Uri("https://localhost:8006/CalculatorService")));
ServicePointManager.ServerCertificateValidationCallback =
((sender, certificate, chain, sslPolicyErrors) =>
{
return true;
});
ICommunicationObject comObject = client as ICommunicationObject;
int result = -1;
try
{
comObject.Open();
result = client.Add(10, 2);
}
catch (Exception ex)
{
}
Console.WriteLine(string.Format("Service say 10 + 2 = {0}", -1));
Console.ReadLine();
服务运行良好,并且在进行 ServicePointManager.ServerCertificateValidationCallback 检查时没有策略错误,并构建了正确的证书链。
我的 CA 位于受信任的根目录中,服务器/客户端证书位于 TrustedPeople 存储中。此外,如果我从浏览器导航到该站点,我会看到返回的页面。没有错误
我已将 IIS 更新为我认为需要的,将证书绑定在 IIS 中
并通过下面的命令行。
我已将 SSL 设置设置为接受证书
并启用匿名身份验证。
有谁知道我没有正确执行哪些步骤或发现有什么问题?我不断收到相同的错误“客户端身份验证方案‘匿名’禁止 HTTP 请求。”
【问题讨论】:
-
我遇到了这个异常,但这是由于我的 ssl 证书过期。
-
WCF 是否有 IIS 的替代方案。我讨厌 IIS,前一天它可以工作,下一天它开始出现各种错误,需要一整天才能解决。