我尝试使用自签名证书进行 WCF。我找到了一些解决方案,但他们需要客户端在连接之前知道 clinet 证书。我想让客户端作为浏览器工作(当浏览器使用 Web 服务器证书时)。我的意思是浏览器在连接之前不知道网络服务器的证书,它可以从网络服务器获取它。我的服务器的 web.config:
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="false" />
<services>
<service behaviorConfiguration="security" name="WebApplicationExchange.UKService">
<endpoint address="" binding="basicHttpBinding" bindingConfiguration="security" contract="WebApplicationExchange.IUKService">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="https://localhost/UKService/UKService.svc" />
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="security">
<serviceMetadata httpGetEnabled="false" httpsGetEnabled="true" />
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="ServiceAuthorization.PasswordValidator,ServiceAuthorization" />
<windowsAuthentication allowAnonymousLogons="false" />
</serviceCredentials>
<serviceAuthorization principalPermissionMode="Custom">
<authorizationPolicies>
<add policyType="ServiceAuthorization.AuthorizationPolicy,ServiceAuthorization" />
</authorizationPolicies>
</serviceAuthorization>
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<basicHttpBinding>
<binding name="security">
<security mode="TransportWithMessageCredential">
<transport clientCredentialType="Basic" />
</security>
</binding>
</basicHttpBinding>
</bindings>
</system.serviceModel>
它适用于网络浏览器。
但客户端显示错误:无法为具有权限“localhost:56389”的安全通道 SSL/TLS 建立信任连接。客户端代码:
System.ServiceModel.EndpointAddress eaSecurity = new System.ServiceModel.EndpointAddress("https://localhost:56389/UKService.svc");
var binding = new System.ServiceModel.BasicHttpBinding();
binding.Security.Mode = System.ServiceModel.BasicHttpSecurityMode.TransportWithMessageCredential;
binding.Security.Transport.ClientCredentialType = System.ServiceModel.HttpClientCredentialType.None;
binding.Security.Message.ClientCredentialType = System.ServiceModel.BasicHttpMessageCredentialType.UserName;
var securityFactory = new System.ServiceModel.ChannelFactory<ServiceReference1.IUKService>(binding, eaSecurity);
securityFactory.Credentials.UserName.UserName = "test";
securityFactory.Credentials.UserName.Password = "test";
myService = securityFactory.CreateChannel();
任何想法如何解决这个问题?
更新: 我深入查看错误堆栈并发现以下内容: System.Security.Authentication.AuthenticationException:根据身份验证结果,远程证书无效。我试过这段代码:
ClientCredentials cc = securityFactory.Endpoint.Behaviors.Find<ClientCredentials>();
cc.UserName.UserName = "test";
cc.UserName.Password = "test";
cc.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None;
但这无济于事。