by Tom Miller
11. January 2010 00:16
SOAP headers are a perfect vehicle for performing authentication for web services. By using SOAP headers we are able to pass our authentication details prior to any method calls. This is a much better solution than passing authentication details for each and every method call.
To implement SOAP headers we must first create a class to hold our authentication details. This class must derive from the System.Web.Service.Protocols.SoapHeader class. It must also expose two string fields called userName and password.
We must then declare a public type of this class within our web service class. Call this AuthenticationHeader.
The above has given the ability for a user to create an instance of our soap header class. Set the credentials (using the userName and password fields) and set the AuthenticationHeader field/property of the web service.
We must then implement an internal function to perform validation of credentials. I've simply hardcoded the example below. We then must decorate our public methods with the [SoapHeader] attribute and set the member name to AuthenticationHeader as well as the IsRequired property to true.
For a basic example of this implementation please see the c# code below:-
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
namespace WebServiceAuthentication
{
/// <summary>
/// Service to demonstrate authentication
/// with SOAP headers.
/// </summary>
[WebService(Namespace = "http://bluweb.co.uk/WebServiceAuthentication")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
// To allow this Web Service to be called from script,
// using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class WebServiceAuthentication : System.Web.Services.WebService
{
[SoapHeader("AuthenticationHeader", Required=true)]
[WebMethod(Description=@"Demonstrates authentication using
SOAP headers for ASP.NET web services")]
public string TestAuthentication()
{
if (!IsAuthenticated())
throw new
InvalidOperationException("Invalid credentials.");
return "You're authenticated";
}
private bool IsAuthenticated()
{
if (AuthenticationHeader != null)
{
if (AuthenticationHeader.userName ==
"username" && AuthenticationHeader.password == "password")
return true;
}
return false;
}
public AuthHeader AuthenticationHeader;
}
public class AuthHeader : SoapHeader
{
public string userName;
public string password;
}
}