拼吾爱程序人生

首页 » 其他编程 » Web Service » Web Service 安全性解决方案(SOAP篇)
cobra - 2007-12-30 9:06:00
文/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建立Asp与Asp.Net之间Session数据桥的应用研究
客户端访问Web Service方法的一个细节
定义web service接口的十点注意事项
创建数据库Web Services
动态调用WebServices
用 SOAP 消息传递返回 ADO 记录集
ASP.NET创建Web服务之声明
根据托管类库创建WebService代码
1
查看完整版本: Web Service 安全性解决方案(SOAP篇)
Modify by pin5i DZNT_ExpandPackage 2.1.3237 2007-2008 pin5i.com