wcf 使用证书

namespace ValidateService
{
    [ServiceContract]
    public interface IEchoClaims
    {
        [OperationContract]
        List<string> Echo();
    }
}

 

---------------server.Contract-------------------------------

 public class EchoClaims:IEchoClaims
    {
        public List<string> Echo()
        {
            List<string> claims = new List<string>();
            var sets = OperationContext.Current.ServiceSecurityContext.AuthorizationContext.ClaimSets;
            foreach (ClaimSet set in sets)
            {
                foreach (Claim c in set)
                {
                    claims.Add(string.Format("{0} - {1} - {2}", c.ClaimType, c.Resource.ToString(), c.Right));

                }
            }
            return claims;
        }
    }

 

---------------server.Service-------------------------------

 

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.serviceModel>
    <services>
      <service name="ValidateService.EchoClaims" behaviorConfiguration="echoClaimBehavior">
        <endpoint address="http://localhost/EchoClaims" 
                  binding="wsHttpBinding" 
                  contract="ValidateService.IEchoClaims"
                   bindingConfiguration="echoClaimBinding"
                  ></endpoint>
      </service>
    </services>

    <bindings>
      <wsHttpBinding>
        <binding name="echoClaimBinding" >
          <security mode="Message">
            <message clientCredentialType="UserName" negotiateServiceCredential="true"/>
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>

    <behaviors>
      <serviceBehaviors>
        <behavior name="echoClaimBehavior">
          <serviceMetadata httpGetEnabled="true" httpGetUrl="http://localhost/EchoClaims/mex"/>
          <serviceCredentials>

            <serviceCertificate  findValue="CN=WCFServer" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectDistinguishedName" ></serviceCertificate>
            
            <userNameAuthentication userNamePasswordValidationMode="Custom"  customUserNamePasswordValidatorType="ValidateService.MyUserNamePasswordValidator,ValidateService"/>
          </serviceCredentials>
            
        </behavior>
      </serviceBehaviors>
    </behaviors>
    
  </system.serviceModel>
</configuration>

 

---------------server.Config-------------------------------

 private void button1_Click(object sender, EventArgs e)
        {
            EchoClaimsClient client = new EC.EchoClaimsClient();

            client.ClientCredentials.UserName.UserName = "lizhch";
            client.ClientCredentials.UserName.Password= "lizhch";

           var list = client.Echo();
           foreach (var l in list)
           {
               MessageBox.Show(l);
           }
        }

 

---------------client.app-------------------------------

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.serviceModel>
        <bindings>
            <wsHttpBinding>
                <binding name="WSHttpBinding_IEchoClaims" closeTimeout="00:01:00"
                    openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
                    bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard"
                    maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
                    messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true"
                    allowCookies="false">
                    <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                        maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                    <reliableSession ordered="true" inactivityTimeout="00:10:00"
                        enabled="false" />
                    <security mode="Message">
                        <transport clientCredentialType="Windows" proxyCredentialType="None"
                            realm="" />
                        <message clientCredentialType="UserName" negotiateServiceCredential="true"
                            algorithmSuite="Default" />
                    </security>
                </binding>
            </wsHttpBinding>
        </bindings>
        <client>
            <endpoint address="http://localhost/EchoClaims" binding="wsHttpBinding"
                bindingConfiguration="WSHttpBinding_IEchoClaims" contract="EC.IEchoClaims"
                name="WSHttpBinding_IEchoClaims" behaviorConfiguration="test">
                <identity>
                    <certificate encodedValue="AwAAAAEAAAAUAAAAVvW+hz9tfv2P/gy5aL/iLNBWVV0gAAAAAQAAAPIBAAAwggHuMIIBW6ADAgECAhB7KzQF+J9Lv0+Y5c/RI46LMAkGBSsOAwIdBQAwEjEQMA4GA1UEAxMHV0NGUm9vdDAeFw0xMzEwMTUxNTU0MzlaFw0zOTEyMzEyMzU5NTlaMBQxEjAQBgNVBAMTCVdDRlNlcnZlcjCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAwVmYxq8gftjxGJLqphFehWf261Np776TaC15qwbXGZj1M24CwH+PZEA3utDU9EFi7wSd66RGj1WqRQRIq9PJB3jujElTkr9SUFRCqNO2MnREX0RHIn00OJRyPPZpzcxy/z1x7+mbWoStwQPs/40olyUw12oCjdtzzLyr0GPIb9UCAwEAAaNLMEkwRwYDVR0BBEAwPoAQ1+tT1RVQCF6Cv5g+TU55iqEYMBYxFDASBgNVBAMTC1Jvb3QgQWdlbmN5ghAb4zc4yi2Ntk2PvtAhzrd3MAkGBSsOAwIdBQADgYEAoLy2c7hcmVRipLQxl7eWeBuoO1gMZD6jFPZxQCJVhSLQdtfsAsHDYkHN8ILaTmQibLU6M34QfJzs1Stxv6WUtVeN8yorbhL+QelPjHYbmX+qYkNeNWRFDVoEyKIfh/uG4f0rT3tgXiJb4Dm+NPOUDlK5YvRY+HHWaEtwpOiK9A0=" />
                </identity>
            </endpoint>
        </client>

      <behaviors>
        <endpointBehaviors>
          <behavior name="test">
            <clientCredentials>
              <serviceCertificate>
                <authentication certificateValidationMode="None" revocationMode="NoCheck"/>
              </serviceCertificate>
            </clientCredentials>
          </behavior>
        </endpointBehaviors>
      </behaviors>
    </system.serviceModel>
</configuration>

 

---------------client.Config-------------------------------

namespace ValidateService
{
     
    public class MyUserNamePasswordValidator:UserNamePasswordValidator
    {
        public override void Validate(string userName, string password)
        {
            if (userName != "lizhch" && password != "lizhch")
            {
                throw new Exception("用户名或是密码错误");
            }
        }
    }
}

 

---------------service.validator-----------------------------------

posted @ 2013-10-16 00:16  feidaochuanqing  阅读(347)  评论(0编辑  收藏  举报