Thursday, August 11, 2016

Authenticate a Webservice using SOAP Header

SOAP Header :

SOAP Header is an optional part of a SOAP message that contain 
Application specific information related to the SOAP message.
It normally contains information like Authentication information,
Transaction Semantics, Routing information, etc.

Let me explain how to make use of SOAP Header for Authenticating
Webservice.

Below is the sample Code :

Service1.asmx.cs (C# Code) :


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

namespace WebService1
{
    /// <summary>
    /// Summary description for Service1
    /// </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 Service1 : System.Web.Services.WebService
    {
        public AuthHeader Authentication;
        [SoapHeader("Authentication", Required = true)]
        [WebMethod]
        public string Concatenate(string a,string b)
        {
            if (Authentication.Username == "KM123" && Authentication.Password == "q@s#d$a^")
                return a + "," + b;
            else
                return "Error : Authentication failed";

        }
    }
    public class AuthHeader : SoapHeader
    {
        public string Username;
        public string Password;
    }
}

I will explain the above code. For using SOAP Header class, we have to
include the namespace, System.Web.Services.Protocols;

Concatenate is the sample Webservice method which gives concatenated
string as the output. In the following post I have explained how to create a
Webservice :


In order to add Authentication to a webservice method we have to create
a class derived from a SOAPHeader class as follows :

public class AuthHeader SoapHeader
{
        public string Username;
        public string Password;
 }

In this example I have included the class within the namespace WebService1
itself . It can be created as a separate class file also.

Above the Concatenate function, first an object of the AuthHeader class
is created as :

 public AuthHeader Authentication;

And then specify SOAPHeader attribute above the Webservice method as :

   [SoapHeader("Authentication", Required = true)]

Inside the webmethod we can validate the credentials as follows:

 public string Concatenate(string a,string b)
  {
       if (Authentication.Username == "KM123" && Authentication.Password == "q@s#d$a^")
            return a + "," + b;
       else
            return "Error : Authentication failed";

  }

No comments:

Post a Comment