Thursday, 16 September 2010

Adding custom HTTP headers with Sys.Net.WebRequestManager

Following from my last post bemoaning the lack of transport-level client crediential authentication when running inside IIS, I've started implementing my own encrypted session-transfer between clients and the server.

I want to to use Http Headers as a primary way of broadcasting session information, and also because it's difficult for a hacker to know exactly what value to add to the http headers if it's been encrypted left, right and centre.  I might extend this to using a cookie as well; but the advantage of relying on http headers is that it means clients other than web browsers will be able to access the services; so long as they can authenticate.

The primary focus of my proof of concepts at the moment are on the AJAX side, both Asp.Net Ajax and 'vanilla' Ajax (e.g. jQuery or direct XmlHttp) - since I know that in Silverlight, for example, I'll be using a different endpoint and can probably add the same authentication data to the message itself.

The scenario is this:

  • A service issues encrypted authentication 'tokens' which a client then sends to other protected services when it makes a request.  These tokens are time limited and have to be refreshed by the client within a certain time period (possibility to make it request-limited as well)
  • A protected service is called by Asp.Net AJAX through use of the auto-generated proxy code that you the ScriptManager control gets - via the /js or /jsdebug endpoint that is added to the webscript-enabled service.

Now, the issue with this is that the proxy code that Asp.Net AJAX is generating is so 'friendly' that the underlying Web requests are abstracted away from your method calls, giving you no direct way of adding any custom headers you might want to add when you make the call.

Never fear - the Sys.Net.WebRequestManager class (part of Microsoft's Asp.Net AJAX client library) provides a hook which gives you the opportunity to examine each and every web request it sends, and even modify it's contents before it leaves the browser.  In fact, setting up the handler is so simple, I'm almost embarrassed to have it sitting at the bottom of such a long preamble...

  1: //method which captures requests and adds headers etc

  2: function InterceptOutgoingRequest(sender, args)

  3: {

  4:   var currentRequest = args.get_webRequest();

  5:   currentRequest.get_headers()["MYCUSTOMHEADER"] = "MYCUSTOMVALUE";

  6: }


  8: //adding the callback to the WebRequestManager

  9: Sys.Net.WebRequestManager.add_invokingRequest(InterceptOutgoingRequest);

The 'sender' parameter will be an instance of the Sys.Net.WebRequestManager, and the 'args' parameter will be an instance of Sys.Net.WebRequest.

Now, every single Asp.Net Ajax call made by the WebRequestManager will call your custom code.

No comments:

Post a Comment