發布日期: 2007-12-30 發布:?cobra?中文編程圖書??Programming Books文/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;
? ? ? ? }
? ? }