webservice安全機制實現方法

 

今天,抽空研究了一下webservice的安全機制,主要一種方法使用SoapHader來實現。使用SoapHeader能夠來控制非法用戶對webservice的調用。下面是具體的實現方法。web

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() 13 {  
} 17 #region user 18 /// <summary> 19 /// 獲取或設置用戶名 20 /// </summary> 21 public string username;
/// <summary> 27 /// 獲取或設置用戶密碼 28 /// </summary> 29 public string userpwd; 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,並編寫相應的代碼ide

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寫的,你們也能夠用別的哈。spa

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, "恭喜你:")); } } }

好了,這就是全部的方法和代碼了,是否是很簡單呢。但願你們多多互相幫助!!code

相關文章
相關標籤/搜索