利用SoapHeader验证web service调用的合法性

本文主要通过示例介绍利用SoapHeader验证web service调用的合法性,
一建立Web service项目,新建一个APIService.asmx
其后台代码如下 

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;

namespace  Downmoon.API
{
    
///   <summary>
    
///  GlobalSetting 的摘要说明
    
///   </summary>
     public   class  APIService : System.Web.Services.WebService
    {
        
public  APIService()
        {
            
// SHeader = new SecuritySoapHeader();
        }
        
public   class  SecuritySoapHeader : SoapHeader
        {
            
#region  Bak
            
private   string  _userName  =   string .Empty;
            
private   string  _pwd  =   string .Empty;
            
/**/
            
///   <summary>
            
///  用户名
            
///   </summary>
             public   string  InvokeUserName
            {
                
get
                { 
return  _userName; }
                
set
                { _userName 
=  value; }
            }
            
/**/
            
///   <summary>
            
///  密码
            
///   </summary>
             public   string  InvokeUserPwd
            {
                
get
                { 
return  _pwd; }
                
set
                { _pwd 
=  value; }
            }
            
#endregion
        }
        
#region  Members
        
public  SecuritySoapHeader SHeader  =   new  SecuritySoapHeader();
        
private   string  _userName  =   string .Empty;
        
private   string  _pwd  =   string .Empty;
        
public   string  InvokeUserName
        {
            
get
            { 
return  _userName; }
            
set
            { _userName 
=  value; }
        }
        
public   string  InvokeUserPwd
        {
            
get
            { 
return  _pwd; }
            
set
            { _pwd 
=  value; }
        }
        
public   static   string  SecurityUserID
        {
            
get
            {
                
try
                {
                    
return  System.Configuration.ConfigurationManager.AppSettings[ " SecurityUserID " ].ToString().Trim();
                }
                
catch
                {
                    
return   " 欢迎与邀月交流,net技术与软件架构 " ;
                }
            }
        }
        
public   static   string  SecurityUserPWD
        {
            
get
            {
                
try
                {
                    
return  System.Configuration.ConfigurationManager.AppSettings[ " SecurityUserPWD " ].ToString().Trim();
                }
                
catch
                {
                    
return   " S2H3I4l5p6q7 " ;
                }
            }
        }

        
#endregion
        
#region   Methods
        
#region  CheckHeader
        
public   bool  IsLegalInvoked()
        {
            
return  IsLegalInvoked( this .SHeader);
        }
        
public   virtual   bool  IsLegalInvoked(SecuritySoapHeader header)
        {
            
bool  bl  =   false ;
            
if  (header  ==   null )
            {
                
// return "您没有设置SoapHeader,不能正常访问此服务!";
                 return  bl;
            }
            
else   if  (header.InvokeUserName  ==   null   ||  header.InvokeUserName.Trim().Length  ==   0   ||  header.InvokeUserPwd  ==   null   ||  header.InvokeUserPwd.Trim().Length  ==   0 )
            { 
return  bl; }
            
if  (header.InvokeUserName.Trim()  !=  SecurityUserID  ||  header.InvokeUserPwd.Trim()  !=  SecurityUserPWD)
            {
                
// return "您提供的身份验证信息有误,不能正常访问此服务!";
                 return  bl;
            }
            bl 
=   true ;
            
return  bl;
        }
        
#endregion

        
#region  ERRORHandle
        
private  clsBasePage bp;
        
public   void  ErrorHandle( string  strMessage)
        {
            
if  (bp  ==   null )
            {
                bp 
=   new  clsBasePage();

            }
            
else
            {
                bp.ErrorStop(strMessage);
                
return ;
            }
        }

        
#endregion

        
#endregion

    }
}



二、添加一个PassPort.asmx,继承APIWebService,主要是为了重用SoapHeader,
调用方法如下( 红色代码部分):
using  System;
using  System.Web;
using  System.Collections;
using  System.Web.Services;
using  System.Web.Services.Protocols;
using  System.ComponentModel;
namespace  Downmoon.API
{
    
///   <summary>
    
///  PassPort 的摘要说明 Downmoon Last Modified 
    
///   </summary>
    [WebService(Namespace  =   " 欢迎与邀月交流,net技术与软件架构.API " )]
    [WebServiceBinding(ConformsTo 
=  WsiProfiles.BasicProfile1_1)]
    
public   class  PassPort : APIService
    {
        
public  PassPort()
        {
        }
        
        
#region  Members
        
#endregion
        
#region   Methods

        
#region 测试安全信息
        [WebMethod(Description = "Test Safe Invoke", EnableSession = true, CacheDuration = 30),SoapHeader("SHeader")]       
        public string HelloWorld()
        {
            if(IsLegalInvoked())
            {
            return "Suceed!";
            }
            else{
                return "Illegal Invoke!";
            }
        }
        #endregion

        
#endregion
    }
}

三、建立Vs2005测试项目,并添加一个测试类(vs2005会自动生成,呵呵)
修改后代码如下:

//  以下代码由 Microsoft Visual Studio 2005 生成。
//  测试所有者应该检查每个测试的有效性。
using  Microsoft.VisualStudio.TestTools.UnitTesting;
using  System;
using  System.Text;
using  System.Collections.Generic;
namespace  TestAPI2005
{
    
///   <summary>
    
/// 这是 Downmoon.API.PassPort 的测试类,旨在
    
/// 包含所有 Downmoon.API.PassPort 单元测试
    
/// </summary>
    [TestClass()]
    
public   class  PassPortTest
    {
        
       
private  TestContext testContextInstance;

        
///   <summary>
        
/// 获取或设置测试上下文,上下文提供
        
/// 有关当前测试运行及其功能的信息。
        
/// </summary>
         public  TestContext TestContext
        {
            
get
            {
                
return  testContextInstance;
            }
            
set
            {
                testContextInstance 
=  value;
            }
        }

        
#region  附加测试属性
        
// 编写测试时,可使用以下附加属性:
         #region  InitTest
        
public   static   string  invokeusername;
        
public   static   string  invokeuserpwd;
        
public   static   string  username;
        
public   static   string  userIP;
        
public   static   string  ConnKey;
        
public   static   string  ConnValue;
        
public   static   int  rowCount;
        
public   static  DateTime ldNow;
        
#endregion
        [ClassInitialize()]
        
public   static   void  MyClassInitialize(TestContext testContext)
        {
            invokeusername 
=   " 欢迎与邀月交流,net技术与软件架构 " ;
            invokeuserpwd 
=   " S2H3I4l5p6q7 " ;
            username 
=   " 欢迎与邀月交流,net技术与软件架构 " ;
            userIP 
=   " 10.103.33.6 " ;
            ConnKey 
=   "" ;
            ConnValue 
=   "" ;
            rowCount 
=   0 ;
            ldNow 
=  DateTime.Now;
        }
        [ClassCleanup()]
        
public   static   void  MyClassCleanup()
        {
            invokeusername 
=   null ;
            invokeuserpwd 
=   null ;
        }
        
// 使用 TestInitialize 在运行每个测试前先运行代码
        
// [TestInitialize()]
        
// public void MyTestInitialize()
        
// {
        
// }
        
// 使用 TestCleanup 在运行完每个测试后运行代码
        
// [TestCleanup()]
        
// public void MyTestCleanup()
        
// {
        
// }
         #endregion

        
#region  HelloWorld () 的测试
        
///   <summary>
        
/// HelloWorld () 的测试
        
/// </summary>
        [TestMethod]
        
public   void  HelloWorldTest()
        {
            
try
            {
                TestAPI.PassPort.PassPort target 
=   new  TestAPI.PassPort.PassPort();
                target.SecuritySoapHeaderValue 
=   new  TestAPI.PassPort.SecuritySoapHeader();
                target.SecuritySoapHeaderValue.InvokeUserName 
=  invokeusername;
                target.SecuritySoapHeaderValue.InvokeUserPwd 
=  invokeuserpwd;
                
string  str  =  target.HelloWorld();
                Console.WriteLine(str);
// Console.WriteLine("Result:" + str);
                Assert.AreEqual(str,  " Suceed! " false );
            }
            
catch  (Exception ex)
            {
                Assert.Fail(
" 单元测试生成错误:  " + ex.Message);
                
/// /Console.WriteLine(ex.Message);
            }
        }
        
#endregion
    }
}

四、在测试管理器中勾选该测试类

右键“运行选中的测试”,即可看到运行结果:通过!
标准输出  Suceed!
此时如果在浏览器中直接调用该服务,将会出现  “Illegal Invoke!”

OK! 结束

以上代码适用于.net 2.0及Vsts 2005。应该也可以适用于vs2003。

你可能感兴趣的:(web Service)