飞狐.net

人的每一步行动,都在书写自己的历史
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

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

Posted on 2007-12-29 23:15  飞狐时代  阅读(2450)  评论(5)    收藏  举报
 闲着没事,研究了一下Web Service的安全性解决方法. 通过SOAP的头信息,通过使用帐号与PIN实现访问Web Method的安全校验.这是一个简便的好方法.

 解决方法:配置SOAP头信息,并将TokenIDPIN写入头信息作为访问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;
}


 

1)       建立带有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;
        }

    }


飞狐.net·书写程序员的历史·创建于2006年12月
Copyright 2005 Silver fox© 飞狐.net All Rights Reserved.