在BasicHttpBinding中的WCF服务中进行身份验证,可以使用以下方法:
在客户端代理类中,设置用户名和密码,并在服务端配置身份验证。
客户端代码:
BasicHttpBinding binding = new BasicHttpBinding();
binding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
EndpointAddress endpointAddress = new EndpointAddress("http://localhost:8000/ServiceModelSamples/Service");
ChannelFactory<ICalculator> channelFactory = new ChannelFactory<ICalculator>(binding, endpointAddress);
channelFactory.Credentials.UserName.UserName = "username";
channelFactory.Credentials.UserName.Password = "password";
ICalculator client = channelFactory.CreateChannel();
服务端配置:
<bindings>
<basicHttpBinding>
<binding name="secureBinding">
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Basic" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<services>
<service name="MyService">
<endpoint address="" binding="basicHttpBinding" bindingConfiguration="secureBinding" contract="ICalculator" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="MyNamespace.CustomUserNameValidator, MyAssembly" />
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
在客户端代理类中,设置证书,并在服务端配置身份验证。
客户端代码:
BasicHttpBinding binding = new BasicHttpBinding();
binding.Security.Mode = BasicHttpSecurityMode.Transport;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;
EndpointAddress endpointAddress = new EndpointAddress("http://localhost:8000/ServiceModelSamples/Service");
ChannelFactory<ICalculator> channelFactory = new ChannelFactory<ICalculator>(binding, endpointAddress);
channelFactory.Credentials.ClientCertificate.SetCertificate(StoreLocation.CurrentUser, StoreName.My, X509FindType.FindBySubjectName, "client.com");
ICalculator client = channelFactory.CreateChannel();
服务端配置:
<bindings>
<basicHttpBinding>
<binding name="secureBinding">
<security mode="Transport">
<transport clientCredentialType="Certificate" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<services>
<service name="MyService">
<endpoint address="" binding="basicHttpBinding" bindingConfiguration="secureBinding" contract="ICalculator" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceCredentials>
<serviceCertificate findValue="MyServiceCertificate" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName" />
<clientCertificate>
<authentication certificateValidationMode="PeerOrChainTrust" />
</clientCertificate>
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
这样,就可以在BasicHttpBinding中的WCF服务中进行身份验证了。
领取专属 10元无门槛券
手把手带您无忧上云