Home   Cover Cover Cover Cover
 

SOAP Header


From Section 7.4.3 of the book

This example shows how to use a SOAP header for supporting user authentication. Only those users that have authenticated themselves by calling the method Login may afterwards call the method GetTime. The SOAP header (see AuthHeader) may contain a cookie, which is generated by the call to Login. This cookie is then used for authentication in the subsequent calls.

Since the purpose of this example is just to demonstrate the use of SOAP headers we use fake methods for the user authentication.

HeaderTimeService.asmx
<%@ WebService Language="C#" Class="HeaderTimeService" %>

using System;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Serialization;

//SOAP header implementation
public class AuthHeader : SoapHeader {
  public string cookie;
}


[WebService(Namespace="http://dotnet.jku.at/time/", Description="SOAP header example")]
public class HeaderTimeService : WebService {
  public AuthHeader curUser;  // header item

  [WebMethod (Description="authenticates a user")]
  [SoapHeader("curUser", Direction=SoapHeaderDirection.Out)]
  public bool Login(string user, string pwd) {
    curUser = new AuthHeader();
    if (Authenticate(user, pwd)) { // user known => create a cookie
      curUser.cookie = CreateCookie(user); 
      return true;
    }
    return false;
  }

  [WebMethod(Description="returns the current time")]
  [SoapHeader("curUser", Direction=SoapHeaderDirection.In)]
  public string GetTime() {
    if (ValidateCookie(curUser.cookie))
      return System.DateTime.Now.ToLongTimeString();
    else
      throw new SoapHeaderException("access forbidden", SoapException.ClientFaultCode);
  }

  // these are fake methods for demonstration purpose
  bool ValidateCookie(string cookie) {
    return cookie == "admin"; 
  }
  
  bool Authenticate(string usr, string pwd) { 
    return usr == "admin" && pwd=="dotnet"; 
  }
  
  string CreateCookie(string user) {
    return user;
  }
}

If you copy this code to a file HeaderTimeService.asmx in a virtual directory of your local machine you can open it with Internet Explorer and get a test page that allows you to invoke the methods Login and GetTime. Use the following data for testing:
   username: admin
   password: dotnet

Alternatively, you can test your web service also with WebService Studio.