Web Service的安全访问【SoapHeader身份认证】
web service安全访问方式可以以下安全措施:
(1)是谁调用?-----soapheader身份认证
(2)来自哪里?-----访问IP认证
(3)加密传输?-----SSL安全访问
本文主要讲解通过SoapHeader来增强Web Service的安全性
(1)自定义soapheader派生类
/// <summary> /// SoapHeader安全验证 /// </summary> public class CredentialSoapHeader : SoapHeader { private string m_username; private string m_password; public string Username { get { return m_username; } set { m_username = value; } } public string Password { get { return m_password; } set { m_password = value; } } public bool VerifyCredentials(string name, string pwd, out string msg) { msg = ""; try { if (name == "test" && pwd == "test") { return true; } else { msg = "对不起,您无权限调用此web服务"; return false; } } catch { msg = "对不起,您无权限调用此web服务"; return false; } } }
(2)添加基于SoapHeader验证的web service接口方法:
CredentialSoapHeader soap = new CredentialSoapHeader(); string msg = string.Empty; #region 退款 /// <summary> /// 统计退款个数 /// </summary> /// <param name="itemid">项目ID</param> /// <param name="productid">产品ID</param> /// <param name="state">退款状态:待处理,处理中,已退款</param> /// <returns></returns> [WebMethod] [SoapHeader("soap")] public int RefundCount(int itemid, int productid, int state) { if (soap.VerifyCredentials(soap.Username, soap.Password, out msg)) { int count = 0; return count; } else { return 0; } }
(3)客户端调用
/// <summary> /// 获取安全凭证 /// </summary> /// <returns></returns> private static CTOCInterface.CredentialSoapHeader GetInterfaceSoapHeader() { CTOCInterface.CredentialSoapHeader header = new CTOCInterface.CredentialSoapHeader(); header.Username = MODEL.SystemConfigInfo.KEY_WTCTOCServiceUsername; header.Password = MODEL.SystemConfigInfo.KEY_WTCTOCServicePassword; return header; } /// <summary> /// 统计退款个数 /// </summary> /// <param name="userlogin"></param> /// <returns></returns> protected static int RefundCount(int itemid, int productid, int state) { using (CTOCInterface.CTOCGroupPurchaseSoapClient client = new CTOCInterface.CTOCGroupPurchaseSoapClient()) { try { return client.RefundCount(GetInterfaceSoapHeader(), itemid,productid,state); } catch { return null; } } }