WCF 客户端 BasicHttpBinding 兼容 HTTPS 和 HTTP
背景:全站HTTPS的时代来了
全站HTTPS,请参考: http://www.cnblogs.com/bugly/p/5075909.html
1. 设置BasicHttpBinding的BasicHttpSecurity模型。
create Binding时通过URI的Scheme来判断是HTTPS还是HTTP.
internal class AtomBinding { private AtomBinding() { } internal static BasicHttpBinding Create(bool isHttps) { return new BasicHttpBinding { MaxReceivedMessageSize = 65536000, ReaderQuotas = new XmlDictionaryReaderQuotas {MaxStringContentLength = 65536000}, // 设置BasicHttpBinding的安全(BasicHttpSecurity类型) Security = { // 安全模型:如果是访问的HTTPS svc,则安全模型设置为Transport,HTTP设置为None(默认) Mode = isHttps ? BasicHttpSecurityMode.Transport : BasicHttpSecurityMode.None, // 信息传输等级安全设置,客户端凭证采用默认的匿名认证 Transport = new HttpTransportSecurity {ClientCredentialType = HttpClientCredentialType.None} } }; } }
2. BasicHttpSecurity类型介绍
- 2.1. Message
Security is provided using SOAP message security. For the BasicHttpBinding, the system requires that the server certificate be provided to the client separately. The valid client credential types for this binding are UserName and Certificate.(客户端需要提供用户名+密码以及证书,Basic Authentication==户名+密码)
- 2.2. None
The SOAP message is not secured during transfer. This is the default behavior.(默认的方式,没有任何安全措施,不能保证信息的完整性和保密性)
- 2.3. Transport
Security is provided using HTTPS. The service must be configured with SSL certificates. The SOAP message is protected as a whole using HTTPS. The service is authenticated by the client using the service’s SSL certificate. The client authentication is controlled through the ClientCredentialType.(通过HTTPS来保证信息安全,客户端的认证取决于ClientCredentialType的配置)
- 2.4. TransportCredentialOnly
This mode does not provide message integrity and confidentiality(这种方式不保证信息的完整性和机密性). It provides only HTTP-based client authentication. Use this mode with caution. It should be used in environments where the transfer security is being provided by other means (such as IPSec) and only client authentication is provided by the Windows Communication Foundation (WCF) infrastructure.
- 2.5. TransportWithMessageCredential
Integrity, confidentiality and server authentication are provided by HTTPS. The service must be configured with a certificate. Client authentication is provided by means of SOAP message security. This mode is applicable when the user is authenticating with a UserName or Certificate credential and there is an existing HTTPS deployment for securing message transfer.(这种方法最安全,但也最繁琐)
3. 客户端忽略对服务器端证书的校验
public AtomResponse Execute(AtomRequest message) { ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, policyErrors) => true; return Channel.Execute(message); }
如果客户端不忽略对服务器端证书的校验,则必须在客户端安装服务器端证书的根证书。