天天看點

WCF 安全性之 自定義使用者名密碼驗證

案例下載下傳

http://download.csdn.net/detail/woxpp/4113172

用戶端調用代碼 通過代理類

代理生成 參見

http://www.cnblogs.com/woxpp/p/6232298.html

X509證書建立

http://www.cnblogs.com/woxpp/p/6232325.html

自定義使用者名密碼驗證需要證書的支援

伺服器端配置代碼

<system.serviceModel>
    <services>
      <service name="WcfServiceLibrary1.Service1" behaviorConfiguration="CustomBehavior">
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8732/WcfServiceLibrary"/>
          </baseAddresses>
        </host>
        <!-- Service Endpoints -->
        <!-- 除非完全限定,否則位址将與上面提供的基址相關 -->
        <endpoint address="net.tcp://localhost:8731/WcfServiceLibrary" binding="netTcpBinding" bindingConfiguration="TestNetTcpBinding" contract="WcfServiceLibrary1.IService1">
          <!-- 
              部署時,應删除或替換下列辨別元素,以反映
              用來運作所部署服務的辨別。删除之後,WCF 将
              自動推斷相應辨別。
          -->
          <identity>
            <dns value="localhost"/>
          </identity>
        </endpoint>
        <!-- Metadata Endpoints -->
        <!-- 中繼資料交換終結點供相應的服務用于向用戶端做自我介紹。 -->
        <!-- 此終結點不使用安全綁定,應在部署前確定其安全或将其删除-->
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
      </service>
    </services>
    <bindings>
      <netTcpBinding>
        <binding name="TestNetTcpBinding">
          <security mode="Message">
            <message clientCredentialType="UserName"/>
          </security>
        </binding>
      </netTcpBinding>
    </bindings>
    <behaviors>
      <serviceBehaviors>
        <behavior name="CustomBehavior">
          <!-- 為避免洩漏中繼資料資訊,
          請在部署前将以下值設定為 false 并删除上面的中繼資料終結點  -->
          <serviceMetadata httpGetEnabled="True"/>
          <!-- 要接收故障異常詳細資訊以進行調試,
          請将以下值設定為 true。在部署前設定為 false 
            以避免洩漏異常資訊-->
          <serviceDebug includeExceptionDetailInFaults="False" />
          <serviceCredentials>
            <serviceCertificate findValue="TestServer" storeName="My" storeLocation="CurrentUser" x509FindType="FindBySubjectName"/>
            <userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="WcfServiceLibrary1.MyCustomValidator,WcfServiceLibrary1"/>
          </serviceCredentials>
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>      

服務端自定義驗證代碼

namespace WcfServiceLibrary1
{
    public class MyCustomValidator : UserNamePasswordValidator
    { 
        public override void Validate(string userName, string password)
        { 
            // validate arguments  
            if (string.IsNullOrEmpty(userName)) 
                throw new ArgumentNullException("userName"); 
            if (string.IsNullOrEmpty(password)) 
                throw new ArgumentNullException("password"); 
            // check if the user is not xiaozhuang 
            if (userName != "abcd1234" || password != "abcd1234")
                throw new SecurityTokenException("使用者名或者密碼錯誤!");
        }
    }
}      
private void btnTest_Click(object sender, EventArgs e)
        {
            //Service1Client client = new Service1Client();
            //txtMessage.Text = client.GetDataUsingDataContract(new WcfServiceLibrary1.CompositeType() { StringValue = "sssss" }).StringValue;

            NetTcpBinding binding2 = new NetTcpBinding();
            binding2.Security.Mode = SecurityMode.Message;
            binding2.Security.Message = new MessageSecurityOverTcp() { ClientCredentialType = MessageCredentialType.UserName };
            EndpointAddress endpoint = new EndpointAddress(new Uri("net.tcp://localhost:8731/WcfServiceLibrary"),
              EndpointIdentity.CreateDnsIdentity("TestServer"));
            ChannelFactory<IService1> factory = new ChannelFactory<IService1>(binding2, endpoint);
            factory.Credentials.ClientCertificate.SetCertificate(StoreLocation.CurrentUser, StoreName.My,
              X509FindType.FindBySubjectName, "TestServer");
            factory.Credentials.UserName.UserName = "abcd1234";
            factory.Credentials.UserName.Password = "abcd1234"; 
            IService1 client = factory.CreateChannel();
            txtMessage.Text = client.GetDataUsingDataContract(new WcfServiceLibrary1.CompositeType() { StringValue = "sssss" }).StringValue;
            //B9DF5B912B8CF8EAB07A7BB9B0D17694522AB0CE
        }      

作者:釋迦苦僧

出處:http://www.cnblogs.com/woxpp

本文版權歸作者和部落格園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接配接。

生活不易,五行缺金,求打點

WCF 安全性之 自定義使用者名密碼驗證