Introduction
Web service development in .NET is very simple, I would say very simple. Numerous examples are available in books. But, unfortunately, those numerous examples as a rule do not say how to write a secured web service. I used to see code examples where username and password were sent into each business method of a web service. It definitely works but I would recommend to separate security logic from business logic. To accomplish this you should incorporate and send username/password in a SOAP header. This will give you an ability to write your own authentication module that will be independent from business logic. As a result, your web service will be more flexible and reliable and you can change or add business methods without changing security logic.
Web service
First, define a class to encapsulate login information:
| public class LoginDetails : SoapHeader
{
public string Username; public string Password;
} |
To use the header in a Web service method, declare a public variable of the header type. Then, add attribute referencing the header class:
| public class MyService : WebService
{
public LoginDetais loginDetais;
[WebMethod] [SoapHeader("loginDetails ", Direction=SoapHeaderDirection.In)] public string GetData() {
bool isAuthenticated= mySecurityManager.Authenticate(loginDetais.Username, loginDetais.Password);
}
} |
However in this case login information is sent as text and is not protected and you should either encrypt Username/ Password or use SSL connection.
Client
Now let’s see an example of consuming the web service. A client sets the header for the proxy class prior to method call that requires it, as shown in the example:
MyService service = new MyService (); LoginDetais myHeader = new LoginDetais (); myHeader.Username = "Test"; myHeader.Password = "123456789"; service.LoginDetais = myHeader; string result =service.GetData(); |
As you can see using custom header is very easy in .NET Web services.