今天,抽空研究了一下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 public string 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, "恭喜你:")); } } }
好了,这就是所有的方法和代码了,是不是很简单呢。希望大家多多互相帮助!!
原文地址:https://www.cnblogs.com/xing-cheng/p/8806593.html
时间: 2024-10-04 13:53:38