文/flyingfox 出处/博客园
闲着没事,研究了一下Web Service的
安全性解决方法. 通过SOAP的头信息,通过使用帐号与PIN实现访问Web Method的安全校验.这是一个简便的好方法.
解决方法:
配置SOAP头信息,并将Token的ID和PIN写入头信息作为访问Web服务的钥匙。
步骤如下:
1) 建立类Credentials,用来作为Token的
验证。
继承于System.Web.Services.Protocols.SoapHeader.
代码如下:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.
UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Services.Protocols;
/**//// <summary>
/// SeviceHelper 的摘要说明
/// </summary>
public class Credentials:System.Web.Services.Protocols.SoapHeader
{
public string AccountID;
public string PIN;
}
2) 建立带有SOAP头信息的Web服务
并定义public Credentials token;
using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
/**//// <summary>
/// myWebService 的摘要说明
/// </summary>
[WebService(Namespace = "
http://tempuri.org/";)]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class myWebService : System.Web.Services.WebService {
public myWebService () {}
public Credentials token;
[WebMethod(Description = "建立带有SOAP头信息的Web服务")]
[SoapHeader("token",Direction =SoapHeaderDirection.In)]
public string GetAccount(string yourname)
{
string myname = yourname;
if (token.AccountID == "12345" && token.PIN == "abcde")
{
return "myname is " + myname + ",account:abcde12345";
}
else
throw new ApplicationException("Authentication Failed!");
//return "nothing_string";
}
}
3) 调用Web服务
代码如下:
protected void btnGet_Click(object sender, EventArgs e)
{
localhost.myWebService mws;
mws=new localhost.myWebService();
localhost.Credentials token = new localhost.Credentials();
token.AccountID = this.txtAccount.Text;
token.PIN = this.txtPIN.Text;
mws.CredentialsValue = token;
try
{
this.txtResult.Text= mws.GetAccount(txtName.Text);
}
catch (System.Exception ex)
{
this.txtResult.Text = ex.Message;
}
}