Friday, June 24, 2011

Security in Web Service

If you want that only authenticated user can call a Web Service method than you have to use SoapHeader for that. Suppose you have a webservice defined as below. You can decorate any method with SoapHeader attribute which you want to secure. In SoaHeader you have to give object name of Validator class.

What is Validator class? When you use SoapHedaer authentication you have to define a User defined class inherited with SoapHeader class. You can define your own variables and properties inside that class to authenticate. This all information related to that Validator class goes in Header section.

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

public class Service:System.Web.Services.WebService
public CValidate objCValidate;

public Service()

public class CValidate:SoapHeader
private string sUser;

public string User
get { return sUser; }
set { sUser = value; }
private string sPassword;

public string Password
get { return sPassword; }
set { sPassword = value; }

public string HelloWorld()
if (objCValidate.User =="Khaleek" &&
objCValidate.Password =="Ahmad")
return "User Name : " +objCValidate.User + " and " +
"Password : " +objCValidate.Password;
return "Invalid credential";

How to call this method

private void CallWebSrvMethod()

localhost.Service objWebService = newlocalhost.Service();
localhost.CValidate objCValidate =

objCValidate .strUserName = “Khaleek”;
objCValidate .strPassword = “Ahmad”;

objWebService.objCValidate =objCValidate;
string str = objWebService.HelloWorld();

The XML structure of an XML Web service response can defined as follows:


User Name : Khaleek and Password : Ahmad

Header tag is optional that contains additional information. Body tag contains the main message. CValidate is the name of class that represent SoapHeader class and inherit SoapHeader. Each element of the CValidate tag is called SoapHeader.

No comments: