Monday, July 26, 2010

Securing Web Methods with username and password in c#

Hi,

When a Web Service is being published to the internet, make sure that the Web Methods have proper authentication set, so that only valid users access the web methods.

To provide username and password to a web method, follow the below procedure:

In the .cs code:

[CODE]

using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
///
/// Summary description for WebService
///


[WebService(Namespace = “http://MyService.com/“)]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

public class MyService : System.Web.Services.WebService
{
public AuthSoapHd spAuthenticationHeader;

public MyService ()
{
//Uncomment the following line if using designed components
//InitializeComponent();
}
public class AuthSoapHd : SoapHeader
{
// Here get the username and password from web.config.
public string strUserName = “user1″;
public string strPassword = “password”;
}
public struct SecurityInfo
{
public string Fname;
public string Lname;
}

[WebMethod,SoapHeader(”spAuthenticationHeader”)]
public SecurityInfo EmpDetails()
{
// Fail the call if the caller is not authorized
if (spAuthenticationHeader.strUserName != “user1″ && spAuthenticationHeader.strPassword != “password”)
{
throw new SoapException(”Unauthorized”, SoapException.ClientFaultCode);
}
SecurityInfo SecurityDetails = new SecurityInfo();
SecurityDetails.Fname = “First Name”;
SecurityDetails.Lname = “Last Name”;
return SecurityDetails;
}

}
[/CODE]

Hope this helps

No comments: