Hibri Marzook Musings on technology and systems thinking

Adding simple authentication to a web service using SOAP headers

If you ever wanted to add a simple username/password authentication to your web service, but ended up with a whole lot of this ?

[WebMethod]
public string HelloWorld(string userName,string password)

Well then, here is a much cleaner way. You can use SOAP headers to pass extra information to a web service. This method uses SOAP headers to pass the user credentials to the web service.

The web service.

We need an object to hold the user credentials. For this example a simple class with username and password properties would suffice. The class should derive from the SoapHeader class.

public class Authentication:SoapHeader
{
    private string _userName;
    private string _password;
	
    public string Password
    {
        get { return _password; }
        set { _password = value; }
    }

    public string UserName
    {
        get { return _userName; }
        set { _userName = value; }
    }
}

In the web service class, declare a public field (or property) of the Authentication type.

WebService(Namespace = “[http://tempuri.org/”)]])
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1,Name=”MyWebService”)]
public class MyWebService : System.Web.Services.WebService {
    public Authentication ServiceCredentials;

In the next step, set up the web method to accept a SOAP header, of the type Authentication, and assign the value to the ServiceCredentials member.

[WebMethod]
    [SoapDocumentMethod(Binding="MyWebService")]
    [SoapHeader("ServiceCredentials") ]
    public string HelloWorld() {
        if (ServiceCredentials.UserName == "test" && 
ServiceCredentials.Password == "world") { return "Hello World"; } else { return "Invalid authentication"; } }

 At the client.

  1. Add the web service reference as usual. Instantiate a new object of the type MyWebService.
    • In addition instantiate a new object of the type Authentication and assign the username and password properties.
      • Next, assign this to the Service credentials property of the MyWebService instance.
        • Call any web method, as you like. </ol> The credentials are being passed with the soap headers, so you don’t need to add the username/password to each and every method. Since, this is done once for the web service, it can be used for multiple calls to any web method in the same service.

        This is how the SOAP XML looks like,

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Header> <Authentication xmlns="http://tempuri.org/"> <Password>string</Password> <UserName>string</UserName> </Authentication> </soap:Header> <soap:Body> <HelloWorld xmlns="http://tempuri.org/" /> </soap:Body> </soap:Envelope>

</font>

By Hibri Marzook

Discuss this post with me on @hibri