ASP.NET中基于soaphead的webservice安全机制

前端技术 2023/09/03 .NET

使用soaphead方法可以在webservice的请求中增加头部信息,当有人调用我们的webservice时,可以通过查询这个请求的头部信息并验证来防止该软件以外的程序调用webservice

一、服务端部分

using System;
using System.Web.Services;
using System.Web.Services.Protocols;

//请注意此命名空间必须有别于代理动态连接库上的命名空间。 
//否则,将产生诸如多处定义AuthHeader这样的错误。 
namespace SoapHeadersCS
{

  //由SoapHeader扩展而来的AuthHeader类 
  public class AuthHeaderCS : SoapHeader
  {
    public string Username;
    public string Password;
  }

  //[WebService(Description=\"用于演示SOAP头文件用法的简单示例\")] 
  public class HeaderService
  {

    public AuthHeaderCS sHeader;

    [WebMethod(Description = \"此方法要求有调用方自定义设置的soap头文件\")]
    [SoapHeader(\"sHeader\")]
    public string SecureMethod()
    {

      if (sHeader == null)
        return \"ERROR:你不是VIP用户!\";

      string usr = sHeader.Username;
      string pwd = sHeader.Password;

      if (AuthenticateUser(usr, pwd))
      {
        return \"成功:\" + usr + \",\" + pwd;
      }
      else
      {
        return \"错误:未能通过身份验证\";
      }
    }

    private bool AuthenticateUser(string usr, string pwd)
    {

      if ((usr != null) && (pwd != null))
      {
        return true;
      }
      return false;
    }
  }
}

二、客户端部分加上验证的请求

WebService webservice = new WebService();
AuthHeaderCS auth = new AuthHeaderCS();
auth.Username = \"vip\";
auth.Password = \"vippw\";
webservice.AuthHeaderCSValue = auth;
textBox1.Text = webservice.SecureMethod();

以上就是基于soaphead的webservice安全机制全部内容,希望能给大家一个参考,也希望大家多多支持phpstudy。

本文地址:https://www.stayed.cn/item/8113

转载请注明出处。

本站部分内容来源于网络,如侵犯到您的权益,请 联系我

我的博客

人生若只如初见,何事秋风悲画扇。