webservice Security Mechanism Based on soaphead in ASP. NET

  • 2021-07-26 07:21:37
  • OfStack

Using soaphead method, we can add header information to the request of webservice. When someone calls our webservice, we can prevent programs other than this software from calling webservice by querying the header information of this request and verifying it

1. The server part


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

// Note that this namespace must be different from the namespace on the broker dynamic connection library.  
// Otherwise, such as multiple definitions will be generated AuthHeader Such a mistake.  
namespace SoapHeadersCS
{

  // By SoapHeader Extended AuthHeader Class  
  public class AuthHeaderCS : SoapHeader
  {
    public string Username;
    public string Password;
  }

  //[WebService(Description=" Used for demonstration SOAP A simple example of header file usage ")] 
  public class HeaderService
  {

    public AuthHeaderCS sHeader;

    [WebMethod(Description = " Object with caller custom settings soap Header file ")]
    [SoapHeader("sHeader")]
    public string SecureMethod()
    {

      if (sHeader == null)
        return "ERROR: You're not VIP Users !";

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

      if (AuthenticateUser(usr, pwd))
      {
        return " Success :" + usr + "," + pwd;
      }
      else
      {
        return " Errors : Failed to authenticate ";
      }
    }

    private bool AuthenticateUser(string usr, string pwd)
    {

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

2. Client Part Plus Authentication Request


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

Related articles: