【转载】WCF 客户端识别认证之UserName认证

原文地址:

http://blog.csdn.net/zxz414644665/article/details/9308055

过程:用户调用service,服务端验证用户传来的用户名和密码(传输过程用X509证书验证及加解密),验证通过则给予调用服务。

1. 生成证书:这里只会生成一个测试用的证书(使用makecert.exe生成),生成完成之后再使用MMC Console给予相应的权限(Manage Private Keys…)。

makecert.exe -sr LocalMachine -ss My -n CN=MyServerCert -sky exchange –pe

2.Server端: 用VS2010 IDE新建一个“WCF Service Application”项目方案,实现我们自己的UserName认证方法,其实就是继承UserNamePasswordValidator(需要添加对System.IdentityModel.dll引用)并重写方法Validate。

[csharp] view plain copy
 
  1. /// <summary>  
  2.     /// MyCustomValidator.cs  
  3.     /// </summary>  
  4.     public class MyCustomValidator: UserNamePasswordValidator  
  5.     {  
  6.         /// <summary>  
  7.         /// Override Validate method to implement custom validation  
  8.         /// </summary>  
  9.         /// <param name="userName">Username</param>  
  10.         /// <param name="password">Password</param>  
  11.         public override void Validate(string userName, string password)  
  12.         {  
  13.             if (string.IsNullOrEmpty(userName))  
  14.             {  
  15.                 throw new ArgumentNullException("userName");  
  16.             }  
  17.   
  18.             if (string.IsNullOrEmpty(password))  
  19.             {  
  20.                 throw new ArgumentNullException("password");  
  21.             }  
  22.   
  23.             // This is for testing purpose  
  24.             if (userName != "Admin" || password != "123456")  
  25.             {  
  26.                 // Why we can't catch this fault exception in client  
  27.                 FaultException fault =  
  28.                     new FaultException(  
  29.                         new FaultReason("UserName or password is wrong!"),  
  30.                         new FaultCode("Error:0x0001"));  
  31.                 throw fault;  
  32.             }  
  33.         }  
  34. }  

在这之后写我们的服务,很简单。

[csharp] view plain copy
 
  1. [ServiceContract]  
  2. public interface IValidationService  
  3. {  
  4.     [OperationContract]  
  5.     string PrintMessage(string message);  
  6.   
  7.   
  8. public class ValidationService : IValidationService  
  9. {  
  10.     public string PrintMessage(string message)  
  11.     {  
  12.         Console.WriteLine("Message = " + message);  
  13.         return message;  
  14.     }  

到这里Server端的代码基本上完成了,接下来就是如何让这些代码能够协同工作,那就需要修改我们的配置文件Web.config,有3个地方需要修改或者添加。

第一,添加binding,这里我们添加wsHttpBinding;

 

[html] view plain copy
 
  1. <!-- Manually added bindings -->  
  2. <bindings>  
  3.   <wsHttpBinding>  
  4.     <binding name="mySecurityBinding">  
  5.       <security mode="Message">  
  6.         <message clientCredentialType="UserName" />  
  7.       </security>  
  8.     </binding>  
  9.   </wsHttpBinding>  
  10. </bindings>  

 第二,添加对UserName认证的配置,即serviceCredentials配置

[html] view plain copy
 
  1. <!-- Manually added credentials -->  
  2. <serviceCredentials>  
  3.   <serviceCertificate findValue="MyServerCert" x509FindType="FindBySubjectName" storeLocation="LocalMachine" storeName="My" />  
  4.   <userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="WCFValidationServer.CustomValidation.MyCustomValidator,WCFValidationServer" />  
  5. </serviceCredentials>  

第三,配置必不可少的endpoint;

[html] view plain copy
 
  1. <!-- Manually added service endpoint -->  
  2. <services>  
  3.   <service behaviorConfiguration="WCFValidationServer.ValidationServiceBehavior" name="WCFValidationServer.ValidationService">  
  4.     <endpoint address="" binding="wsHttpBinding" contract="WCFValidationServer.IValidationService"   
  5.               bindingConfiguration="mySecurityBinding">  
  6.       <identity>  
  7.         <dns value="MyServerCert" />  
  8.       </identity>  
  9.     </endpoint>  
  10.     <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />  
  11.   </service>  
  12. </services>  

至此,Server端还需要做最后一件事情,即host到IIS中,这里就不多说了,测试host成功既可。

3.    Client端:同样的,用VS2010新建一个“ASP.NET Web Application”项目方案,添加对WCF service的引用,IDE会自动添加WCF的相关配置工作,这里有一点需要注意,因为我们的证书并不是真正意义上的证书,只是测试生成的,所以这个证书并不会通过验证,所以当我们客户端访问服务的时候会报错的(具体的错误不说了,自己试了就知道),我们需要在客户端添加一个自己的X509证书验证方法,这里为了测试方面,我们重新的Validate方法是空的,即不做任何认证判断。

[csharp] view plain copy
 
  1. public class MyX509Validator : X509CertificateValidator  
  2. {  
  3.     public override void Validate(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate)  
  4.     {  
  5.           
  6.     }  
  7. }  

好了,代码完成,同样我们需要修改客户端的Web.config配置文件来让这段代码起作用,添加如下的behavior,并将client的endpoint的behaviorConfiguration设置为我们添加的。

[html] view plain copy
 
  1. <client>  
  2.   <endpoint address="http://localhost:8000/ValidationService.svc"  
  3.     binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IValidationService"  
  4.     contract="WCFValidationService.IValidationService" name="WSHttpBinding_IValidationService" behaviorConfiguration="myClientBehavior">  
  5.     <identity>  
  6.       <dns value="MyServerCert" />  
  7.     </identity>  
  8.   </endpoint>  
  9. </client>  
  10.   
  11. <behaviors>  
  12.   <endpointBehaviors>  
  13.     <behavior name="myClientBehavior">  
  14.       <clientCredentials>  
  15.         <serviceCertificate>  
  16.           <authentication certificateValidationMode="Custom" customCertificateValidatorType="WCFValidationClient.MyX509Validator,WCFValidationClient" />  
  17.         </serviceCertificate>  
  18.       </clientCredentials>  
  19.     </behavior>  
  20.   </endpointBehaviors>  
  21. </behaviors>  

好了,至此我们的整个项目就完成了。客户端的界面及调用service就不说了,可以看我上载的源代码

原文地址:https://www.cnblogs.com/zhaiyf/p/8493140.html