Web Service 安全性解决方案(SOAP篇)

文/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;
        }
    }

 感谢原创者的辛勤劳动,希望对您有所帮助,转载请注明原出处。
 您可能对 [Web Service] 的这些文章也感兴趣:

通过Web Services上传和下载文件  实现Web Service依赖倒置
在Web Services中管理Sessions  页面前台通过JS访问WEB SERVICES,以及如何处理返回结果
Javascript调用Webservice的汇集  Web Service学习笔记:类和结构体解析
ASP.NET创建Web服务之发布和部署  SharePoint Web Services入门
HTTP 安全性和 ASP.NET Web 服务  ASP.NET创建Web服务之XML基础结构
Web Service学习笔记:WebService特性和数组类型解析  使用WCF的Web编程模型开发REST风格的Web Service
利用Web Services保持Http环境下的连接状态  基于Web Services建立Asp与Asp.Net之间Session数据桥的应用研究
实现COM组件向Web Services的转变  Microsoft Releases Web Service Software Factory
改善Web Service安全性:WCF指导包  创建数据库Web Services
ASP.NET创建Web服务之管理Web服务状态  ASP.NET创建Web服务之声明