代码改变世界

WebService 简单安全验证

  温森特  阅读(15157)  评论(0编辑  收藏  举报

        最近新接了一个需要调用第三方WebService的项目,看到这个第三方WebService被调用的时候,需要授权用户名和密码,于是自己也想对WebService的安全授权这个方面进行了一下研究,以前调用的WebService大部分都是局域网内部调用,几乎没有什么权限需要增加的,今天借此机会,深入研究了一下,发现实现起来还是挺容易的。

       基本原理就是利用SoapHeader 类,继承该类,然后在我们公布的方法上加上对应的标签,呵呵。现在做一个Demo程序,进行验证。我们首先衍生一个自己的子类,暂命名为SecurityHeader ,在该类中需要增加一个公共属性,详看如下代码

 

  public class SecurityHeader : SoapHeader

复制代码
    {
        
public string SecurityKey
        {
            
get;
            
set;
        }
    }
复制代码

 

      在WebService 中对该SoapHeader 的调用实现,也是比较容易理解的,详看一下代码就可以很好的理解了,代码中只需对SoapHeader进行验证就可以了。如果我们不增加SoapHeader,其实质就是普通的Public 类型的WebService 。调用的时候完全的公开的,不需要任何的验证信息。

 

复制代码
 /// <summary>
    
/// Summary description for Integration
    
/// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo 
= WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(
false)]
    
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    
// [System.Web.Script.Services.ScriptService]
    public class Integration : System.Web.Services.WebService
    {
        
public SecurityHeader securityKey = new SecurityHeader();

        [WebMethod]
        [SoapHeader(
"securityKey")]
        
public string HelloWorld(string show)
        {
            
if (securityKey.SecurityKey.Equals("850"))
            {
                
return "This is security webservice " + show;
            }
            
else
            {
                
return "Sorry,You didn't permissions!";
            }
        }

        [WebMethod]
        
public string HelloPanda(string show)
        {
            
return "This is public webservice  " + show;
        }

    } 

复制代码

   

       验证程序代码如下:

     

复制代码
 class Program
    {
        
static void Main(string[] args)
        {
            PandaRGIntegration.SecurityHeader header 
= new PandaRG.Listrak.PandaRGIntegration.SecurityHeader();
            header.SecurityKey 
= "850";

            PandaRGIntegration.IntegrationSoapClient client 
= new PandaRG.Listrak.PandaRGIntegration.IntegrationSoapClient();
            System.Console.WriteLine(client.HelloWorld(header,
"Vincent"));
            System.Console.WriteLine(client.HelloPanda(
"Vincent"));
            System.Console.Read();
        }
    }
复制代码

 

调用结果: 


 

      当我们修改 header.SecurityKey = "8500"时结果

 

       整个完整例子到此实验完毕。感性趣的,也可以自己试验一下。

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示