Posted on Leave a comment

Example using Soap Header username & password

Example of a minimal implementation that includes Soap username and password.

First create the service:

-------------------------- websvc.cs ----------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Services;
using System.Web.Services.Protocols;

namespace wstest
{
   [WebService(Namespace = "http://tempuri.org/")]
   [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
   [System.ComponentModel.ToolboxItem(false)]
   public class Service1 : System.Web.Services.WebService
   {
      public ServiceAuthHeader CustomSoapHeader;

      [WebMethod]
      [SoapHeader("CustomSoapHeader")]
      public string HelloWorld()
      {
         ServiceAuthHeaderValidation.Validate(CustomSoapHeader);
         return "Hello World";
      }
   }


   public class ServiceAuthHeader : SoapHeader
   {
      public string Username;
      public string Password;
   }
 
 
   public class ServiceAuthHeaderValidation
   {
      public static bool Validate(ServiceAuthHeader soapHeader)
      {
         if (soapHeader == null)
         {
            throw new NullReferenceException("No soap header was specified.");
         }
         else if (soapHeader.Username == null || soapHeader.Password == null)
         {
            throw new NullReferenceException("Username and password are required.");
         }
         else if (soapHeader.Username != "myuser" || soapHeader.Password != "mypass")
         {
            throw new NullReferenceException("Provide correct values for username and password.");
         }
         return true;
      }
   }
   
}

-------------------------- websvc.cs ----------------------

Launch the service, create a console app, right click “Service References” and select “Add Service Reference”, paste url to WSDL for web service.

-------------------------- client.cs ----------------------

using System;
using System.Collections.Generic;

namespace ConsoleApplication2
{
   class Program
   {
      static void Main(string[] args)
      {
         string s;
         ServiceReference1.Service1SoapClient svc = new ServiceReference1.Service1SoapClient();
         ServiceReference1.ServiceAuthHeader hdr = new ServiceReference1.ServiceAuthHeader();
         hdr.Username = "myuser";
         hdr.Password = "mypass";
         s = svc.HelloWorld(hdr);
         Console.WriteLine(s);
      }
   }
}

-------------------------- client.cs ----------------------
Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.