SoapHeader身份认证 访问IP认证 SSL安全访问
一、SoapHeader 1.定义SoapHeader派生类 public class MySoapHeader : System.Web.Services.Protocols.SoapHeader { private string _UserID = string.Empty; private string _PassWord = string.Empty; public MySoapHeader() { } public MySoapHeader(string nUserID,string nPassWord) { Initial(nUserID,nPassWord); } public string UserID { get{return _UserID;} set{_UserID = value;} } public string PassWord { get{return _PassWord;} set{_PassWord = value;} } private void Initial(string nUserID,string nPassWord) { UserID = nUserID; PassWord = nPassWord; } private bool IsValid(string nUserID,string nPassWord,out string nMsg) { nMsg = ""; try { if(nUserID == "admin" && nPassWord == "admin") return true; else { nMsg = "对不起,你无权调用此Web服务。"; return false; } } catch { nMsg = "对不起,你无权调用此Web服务。"; return false; } } public bool IsValid(out string nMsg) { return IsValid(_UserID,_PassWord,out nMsg); } } 2.添加基于SoapHeader验证的Web Service接口方法 [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [ToolboxItem(false)] public class WebService_Soap : System.Web.Services.WebService { //声明Soap头实例 public MySoapHeader myHeader = new MySoapHeader(); //普通方法,不需要SoapHeader验证 [WebMethod(Description = "根据产品编号查询产品的价格")] public string GetProductPrice(string ProductId) { Products pro = new Products(); return pro.GetPrice(ProductId); }
//需要SoapHeader验证 [SoapHeader("myHeader")] [WebMethod(Description="根据产品编号查询产品的价格",EnableSession = true)] public string GetProductPrice2(string ProductId) { string msg = ""; //验证是否有权访问 if(!myHeader.IsValid(out msg)) { return msg;//返回错误消息 } Products pro = new Products(); return pro.GetPrice(ProductId); } } 3.客户端调用具有SoapHeader的Web Service //创建myService对象 ProductServiceSoap.WebService_Soap service = new ProductServiceSoap.WebService_Soap(); //创建soap头对象 ProductServiceSoap.MySoapHeader header = new ProductServiceSoap.MySoapHeader(); //设置soap头设置 header.PassWord = "admin"; header.UserID = "admin"; service.MySoapHeaderValue = header; //调用web方法 string strPrice = service.GetProductPrice2("001");
二、 访问IP认证
bool ValidateIP(int UserID, out string exceptionInfo)
{
exceptionInfo = "";
string uip = HttpContext.Current.Request.UserHostAddress;
Common dal = new Common();
List<string> ips = dal.GetPermitIp(UserID);//得到该用户ID所允许的IP列表
if(ips == null || ips.Count == 0)
{
exceptionInfo = "调用Web服务的客户端IP未被允许,无法访问!";
return false;
}
if(ips.Contains(uip))//允许IP列表中包含该IP
{
return true;
}
exceptionInfo = "调用Web服务的客户端IP未被允许,无法访问!";
return false;
}
在具体Web方法里调用该方法检查用户访问者是否是以我们允许的IP进行访问的,以确保安全。
优点:简单,防止非指定客户机访问。
缺点:IP是可以伪造的;维护IP地址表比较烦琐。且只适合于固定IP访问者的情况。
三、SSL安全访问 SSL(Security Socket Layer)的中文全称是加密套接字协议层,它位于HTTP协议层和TCP协议层之间,用于建立用户与服务器之间的加密通信,确保所传递信息的安全性,同时SSL安全机制是依靠数字证书来实现的。 SSL基于公用密钥和私人密钥,用户使用公用密钥来加密数据,但解密数据必须使用相应的私人密钥。使用SSL安全机制的通信过程如下:用于与IIS服务器建立连接后,服务器会把数字证书与公用密钥发送给用户,用户端生成会话密钥,并用公用密钥对会话密钥进行加密,然后传递给服务器,服务器端用私人密钥进行解密,这样用户端和服务器端就建立了一条安全通道,只有SSL允许的用户才能与IIS服务器进行通信。
以下图片省略......