Tuesday, April 14, 2009

asp.net webservice SoapHeader Authentication

After long time,this is my second attempt to authenticate the webservice using SoapHeader.My System Architect team asked me to work aroud on this issue.Its works atlast :)-


SoapAuthenticateService.cs
*******************************
using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(Name = "TestService", ConformsTo = WsiProfiles.BasicProfile1_1)]

public class SoapAuthenticateService : System.Web.Services.WebService
{

public UserAuthorise name;
public SoapAuthenticateService()
{


}

[WebMethod]
[SoapDocumentMethod(Binding = "TestService")]
[SoapHeader("name")]
public string GetString()
{
if (checkUser())
{
return "Authenticated Successfully";
}
else
{
return " You are not authorised yet !";
}


}

public bool checkUser()
{
if (name.userName == "Murugesan" && name.password == "12345")
{
return true;
}
else
{
return false;
}

}

}
________________________________________________________________________________

UserAuthorise.cs
**************************

public class UserAuthorise : System.Web.Services.Protocols.SoapHeader
{

public string userName;
public string password;


}
__________________________________________________________________________________

Service.asmx
***********************

<%@ WebService Language="C#" CodeBehind="~/App_Code/SoapAuthenticateService.cs" Class="SoapAuthenticateService" %>


Consumer Application code :

SoapAuthenticateService ap = new SoapAuthenticateService();
UserAuthorise u = new UserAuthorise();
u.userName = "Murugesan";
u.password = "12345";
ap.UserAuthoriseValue = u;

Response.Write(ap.GetString());

instead of hard coded user name and password,you can use the DB or XML as datasource.