sen

导航

学习笔记之 WCF安全(3) 数字证书+ 自定义验证(wshttpBinding)

Posted on 2009-11-16 09:38  sen  阅读(798)  评论(0)    收藏  举报

在前面两节学习的基础上!

在Host端加入System.IdentityModel; / System.IdentityModel.Selectors;

image

新加一个验证类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
/*加入下面几个命名空间*/
using System.IdentityModel;
using System.IdentityModel.Tokens;
using System.IdentityModel.Selectors;  

namespace WCFHost
{
    class Validate :UserNamePasswordValidator//继承用户用户名密码设定
    {
        public override void Validate(string userName, string password)
        {
            if (userName != password )
            {

                Console.WriteLine("Login failed !:{0}", userName);
                throw new SecurityTokenException("Unknown Username or Password");
            }
            else
            {
                Console.WriteLine("Login sucessfully !:{0}", userName);
            }
        } 

    }
}

在前面一节的配置文件的基础上加入指定用户自定义验证方式的类,配置文件如下:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.web>
    <compilation debug="true" />
  </system.web>
  <system.serviceModel>
    <services>
      <service name="WCF.Service1" behaviorConfiguration="WCF.Service1Behavior">
        <host>
          <baseAddresses>
            <add baseAddress = "https://192.168.172.1:99/" />
          </baseAddresses>
        </host>
        <endpoint address ="myWCF" binding="wsHttpBinding" contract="WCF.IService1" bindingConfiguration ="myHttpBinding">
          <!--<identity>
            <dns value="localhost"/> 
          </identity>-->
        </endpoint>
        <endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange"/>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="WCF.Service1Behavior">
          <serviceMetadata httpsGetEnabled="True"/>
          <serviceDebug includeExceptionDetailInFaults="False" />
          <serviceCredentials >
            <serviceCertificate storeName="My" storeLocation="LocalMachine" x509FindType="FindBySubjectName" findValue="WCFServerPK" />
            <!-- 加入下面一句, 指定自定义的验证方式  
            WCFHost(这个是命名空间).myValidate(这个是类名) , WCFHost(这个是工程名),其实就是指定哪个文件下面的哪个命名空间下面的验证类 -->
            <userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType ="WCFHost.myValidate,  WCFHost"/> 
          </serviceCredentials>
          
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <bindings >
      <wsHttpBinding >
        <binding name ="myHttpBinding">
          <security mode="Transport">
            <transport clientCredentialType ="Basic"/><!--验证方式还是基本验证-->
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>
  </system.serviceModel>
</configuration>

更新前一章节的客户端service Reference ,其实配置文件不发改变其它的也未发生改变,客户端基本上也没有乍么修改,只是为了验证通过,修改了一下用户名密码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;

namespace WCFClient
{
    class Program
    {
        static void Main(string[] args)
        {
            myWCF.Service1Client client = new WCFClient.myWCF.Service1Client();
            /*加入下面两名做验证 和前一节的代码一样,只是不是用windows的用户的验证*/
            client.ClientCredentials.UserName.UserName = "Asen";
            client.ClientCredentials.UserName.Password = "Asen";
            System.Net.ServicePointManager.ServerCertificateValidationCallback +=myCertificateValidate;
            Console.Write(client.GetData("客戶端傳過去的值!"));
            Console.Read();  
        }
        private static bool myCertificateValidate( object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error)
        {
            // trust any certificate!!!
            System.Console.WriteLine("Warning, trust any certificate");
            return true;
        }
    }
}

 

至此一个自定义的验证就算完成了!

这里关键是创建了一个自定义验证类,及把类加入到配置文件中去