WCF 身份验证 通过检查客户端IP

来源:互联网 发布:数据库业务流程图 编辑:程序博客网 时间:2024/05/21 12:43

WCF 身份验证

功能描述:

服务运行的时候,通过配置文件获取所有可访问SOA端的服务IP。每次客户调用服务时获取IP对比判定通过。

以下是获取客户端IP的代码:

 /************************************************************************************* * 代码:吴蒋 * 时间:2012.02.07 * 说明:安全类 * 其他: * 修改人: * 修改时间: * 修改说明: ************************************************************************************/using System.ServiceModel;using System.ServiceModel.Channels;namespace Tools{    public class Safe    {        public static Safe Instance()        {            return new Safe();        }        public string ClientIp()        {                         OperationContext context = OperationContext.Current;            MessageProperties properties = context.IncomingMessageProperties;            RemoteEndpointMessageProperty endpoint = properties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;            return endpoint.Address;        }        public string ClientPort()        {             OperationContext context = OperationContext.Current;            MessageProperties properties = context.IncomingMessageProperties;            RemoteEndpointMessageProperty endpoint = properties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;            return endpoint.Port.ToString();        }        public string ClientIpAndPort()        {            OperationContext context = OperationContext.Current;            MessageProperties properties = context.IncomingMessageProperties;            RemoteEndpointMessageProperty endpoint = properties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;            return endpoint.Address + ";" + endpoint.Port.ToString();        }    }}

XML 存放可访问IP

<?xml version="1.0" encoding="utf-8" ?><configuration>  <ip>192.168.0.71</ip>  <ip>192.168.0.6</ip>  <ip>127.0.0.1</ip>  <ip>192.168.0.72</ip>  <ip>192.168.0.136</ip>  <ip>192.168.0.3</ip></configuration>


 

页面加载时获取所有可访问IP

 public static DataTable dtRunIp;        public static string MapPath = ConfigurationManager.ConnectionStrings["configPath"].ConnectionString;                protected void Application_Start(object sender, EventArgs e)        {            dtRunIp = XMLHelper.XmlHelper.Instance().ReadRunIP(MapPath + "/Config/RunConfig.config", "//configuration/ip");        }


 

#region 特殊函数        /// <summary>        /// 匹配允许访问IP        /// </summary>        /// <param name="path">文件路径</param>        /// <param name="node">节点名称</param>        /// <returns>转换为DataTable</returns>        public DataTable ReadRunIP(string path, string node)        {            XmlDocument doc = new XmlDocument();            doc.Load(path);            DataTable dt = new DataTable();            dt.Columns.Add("ip", typeof(string));            XmlNodeList xnlist = doc.SelectNodes(node);            if (xnlist.Count > 0)            {                for (int i = 0; i < xnlist.Count; i++)                {                    DataRow dr = dt.NewRow();                    dr["ip"] = xnlist[i].InnerText;                    dt.Rows.Add(dr);                }            }            return dt;        }        #endregion


判断IP许可

public static bool IsCanRead()        {            string clientIp = Tools.Safe.Instance().ClientIp();            bool r = false;            if (Global.dtRunIp.Rows.Count > 0)            {                for (int i = 0; i < Global.dtRunIp.Rows.Count; i++)                {                    if (clientIp == Global.dtRunIp.Rows[i]["ip"].ToString())                    {                        r = true;                    }                }            }            return r;        }


 

在服务中的应用:

[ServiceContract]    public class SOAControl    {        string msgr = "无访问权限、服务器积极拒绝";        //获取xml文档        [OperationContract]        public string GetXML(ref string msg)        {                    if (Certificate.IsCanRead())            {                              return XmlHelper.Instance().XmlDocumentToString(Global.MapPath + "/Control/Control.config".ToString());            }            else            {                msg = msgr;                return null;            }        }


WCF的配置文件设置

<?xml version="1.0"?><configuration>  <system.serviceModel>    <bindings>      <wsHttpBinding>        <binding name="NoneSecurity"        maxBufferPoolSize="12000000" maxReceivedMessageSize="12000000" useDefaultWebProxy="false">          <readerQuotas maxStringContentLength="12000000" maxArrayLength="12000000"/>          <security mode="None"/>        </binding>      </wsHttpBinding>    </bindings>    <behaviors>      <serviceBehaviors>        <behavior name="Control.Service.SOAControlBehavior">          <serviceMetadata httpGetEnabled="true"/>          <serviceDebug includeExceptionDetailInFaults="false"/>        </behavior>      </serviceBehaviors>    </behaviors>    <services>      <service behaviorConfiguration="Control.Service.SOAControlBehavior" name="Control.Service.SOAControl">        <endpoint address="" binding="wsHttpBinding" contract="Control.Service.SOAControl" bindingConfiguration="NoneSecurity">          <identity>            <dns value="localhost"/>          </identity>        </endpoint>        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>      </service>    </services>  </system.serviceModel></configuration>


注意事项,在客户端访问的时候是IP6的,可以直接将IP保存到XML文件中,或禁用IP6

源码下载 http://download.csdn.net/detail/wujiang1984/4131313点击打开链接

	
				
		
原创粉丝点击