保证WebService的安全

给第三方做了个webservice,因为都是内部系统没有用到什么身份验证,今晚突发奇想,翻书看了一下,有几个个人认为不是很好的方法,现在展示出来,只求抛砖引玉

通过SoapHeader来增强WebService的安全性

  通过SoapHeader可以让具有指定用户口令的用户来访问自己的WebService接口。

  SoadHeader派生类实现

ContractedBlock.gif ExpandedBlockStart.gif 代码
 
   
/// <summary>
/// Summary description for SoapHeader
/// </summary>
public class MySoapHeader:System.Web.Services.Protocols.SoapHeader
{

private string _userID = string .Empty;

public string UserID
{
get { return _userID; }
set { _userID = value; }
}
private string _userName = string .Empty;

public string UserName
{
get { return _userName; }
set { _userName = value; }
}
public MySoapHeader()
{
//
// TODO: Add constructor logic here
//
}

public MySoapHeader( string userID, string pwd)
{
this .UserID = userID;
this .UserName = pwd;
}

private bool IsValid( string userID, string pwd, out string exceptionMsg)
{
exceptionMsg
= "" ;
try
{
if (userID == " Alex " && pwd == " hap " )
{
return true ;
}
else
{
exceptionMsg
= " 对不起,你无权调用该Web服务 " ;
return false ;
}
}
catch
{
exceptionMsg
= " 对不起,你无权调用该Web服务 " ;
return false ;
}
}

public bool IsValid( out string exceptionMsg)
{
return IsValid( this .UserID, this .UserName, out exceptionMsg);
}
}

 

  添加基于SoapHeader验证的WebService实现

ContractedBlock.gif ExpandedBlockStart.gif 代码
 
   
[WebService(Namespace = " http://tempuri.org/ " )]
[WebServiceBinding(ConformsTo
= WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {

public WebService () {

// Uncomment the following line if using designed components
// InitializeComponent();
}

// 实例化Soap头实例
public MySoapHeader myHeader = new MySoapHeader();

[WebMethod]
public string HelloWorld()
{
string exceptionMsg = "" ;
if ( ! myHeader.IsValid( out exceptionMsg))
{
return exceptionMsg; // 返回错误信息
}
else // 验证通过
{
return " Hello World " ;
}
}
}

 

  客户端调用具有SoapHeader的WebService

 
  
protected void Page_Load( object sender, EventArgs e)
{
WebService ws
= new WebService();
ws.myHeader
= new MySoapHeader( " Alex " , " hap " );
ws.HelloWorld();
}

 

感觉就是做了个身份验证

  还有一些方法,可以通过IP等来限制,主要是IP是可以伪造的,还有可以采用SSL实现加密传输,这个主要是要申请证书,需要在服务器安装证书服务等等,对站点的整体性能有影响,因为它需要进行多次加解密的数据处理。

  如果有人有比较好的方法,还望不吝赐教

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值