Friday, November 2, 2012

Using URLRewriter in IIS to Munge a Cookie Header

Updating a header using the URLRewrite Module in IIS is fairly straight forward--but distilling how to do it from the documentation is a bit of a pain.  A friend of mine was working on it and ended up with 30 browser windows up as he sorted out how to do it.  So in honor of that monumental effort this humble post distills what was learned into a simple example of how to remove a cookie from the cookie header.  So for example, imagine the request being made from the client to the web server with the following cookie header:
Cookie: foo1=x; foo2=y; foo3=z
 The goal is to remove "foo2-y;" so the header changes to this:

Cookie: foo1=x; foo3=z
Here is a rule that will do it:
<rule name="Change 'foo2' Cookie Value" stopProcessing="false">
  <match url="^(.*)" />
    <add input="{HTTP_COOKIE}" pattern="(.*)(foo2=.\; )(.*)" />
    <set name="HTTP_COOKIE" value="{c:1}{c:3}" />
  <action type="Rewrite" url="{R:0}" />
Note that sometimes HTTP_COOKIE is surrounded by curly braces, and sometimes not. Also the action type is "Rewrite"--even though the URL itself is not being changed. Finally, the HTTP_COOKIE must be an "allowed server variable".  You can use the URL Rewrite applet in the IIS Manager to add it, or run something like this from powershell:
Try{$NewServerVariable = Add-WebConfiguration /system.webServer/rewrite/allowedServerVariables -atIndex 0 -value @{name="HTTP_COOKIE"}}Catch{}
or from an administrative command line prompt:
%WINDIR%\System32\inetsrv\appcmd.exe set config  -section:system.webServer/rewrite/allowedServerVariables /+"[name='HTTP_COOKIE']" /commit:apphost

I'll leave it to the reader to improve the rule to handle cases where there are no other keys in the cookie, or if the value of foo2 is more characters than one, etc.