webservice安全機制實現方法
阿新 • • 發佈:2018-04-12
profile 對不起 form public hds pcl generic AR bject
今天,抽空研究了一下webservice的安全機制,主要一種方法使用SoapHader來實現。使用SoapHeader可以來控制非法用戶對webservice的調用。下面是具體的實現方法。
1:首先我們自定義一個類MySoapHeader,需要繼承System.Web.Services.Protocols.SoapHeader 這個類
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using System.Web.Services.Protocols;6 7 namespace WebService.Common 8 { 9 public class MySoapHeader : SoapHeader 10 { 11 12 public MySoapHeader(string username,string userpwd) 13 { 14 this.username = username; 15 this.userpwd = userpwd; 16 } 17 #region user 18 ///<summary> 19 /// 獲取或設置用戶名 20 /// </summary> 21 public string username 22 { 23 get { return username; } 24 set { username = value; } 25 } 26 /// <summary> 27 /// 獲取或設置用戶密碼 28 /// </summary> 29 publicstring userpwd 30 { 31 get { return userpwd; } 32 set { userpwd = value; } 33 } 34 35 36 #endregion 37 38 /// <summary> 39 /// 驗證客戶端傳來的用戶信息 40 /// </summary> 41 /// <param name="in_username"></param> 42 /// <param name="in_userpwd"></param> 43 /// <returns></returns> 44 public bool ValideUser(string in_username, string in_userpwd) 45 { 46 47 if (in_username == "admin" && in_userpwd == "admin" ) 48 { 49 return true; 50 } 51 else 52 { 53 return false; 54 } 55 } 56 57 } 58 }
2:添加webservice,並編寫相應的代碼
using System; using System.Collections.Generic; using System.Web; using System.Web.Services; /// <summary> ///WebService 的摘要說明 /// </summary> [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class WebService : System.Web.Services.WebService { public MySoapHeader header; ////定義用戶身份驗證類變量header [WebMethod] [System.Web.Services.Protocols.SoapHeader("header")]//用戶身份驗證的soap頭 public string HelloWorld(string contents) { //驗證是否有權訪問 if (header.ValideUser(header.username, header.userpwd)) { return contents + "調用服務成功"; } else { return "對不起,您沒有權限訪問"; } } }
3:客戶端調用。這裏我用的是webform寫的,大家也可以用別的哈。
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using WebApplication2.ServiceReference1; namespace WebApplication1 { public partial class Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { HDSServiceSoapClient test = new HDSServiceSoapClient(); MySoapHeader heder = new MySoapHeader(); heder.username = "admin"; heder.userpwd = "admin"; Response.Write(test.HelloWorld(heder, "恭喜你:")); } } }
好了,這就是所有的方法和代碼了,是不是很簡單呢。希望大家多多互相幫助!!
webservice安全機制實現方法