Using the URL Rewrite module to set your cookies to HttpOnly
Gary Sherman
January 20, 2011

A question recently arose about how to set a cookie to be HttpOnly. An HttpOnly cookie is one that cannot be accessed through client-side script. Any information contained in an HTTP-only cookie is less likely to be disclosed to a hacker or a malicious Web site. The use of HTTP-only cookies is one of several techniques that, when used together, can mitigate the risk of cross-site scripting.

Setting a cookie to be HttpOnly

One way to set a cookie to be HttpOnly is to change how you define it.

Rather than something like this:

Response.Cookies("mycookie") = “foo”;

We can do this:

Response.AddHeader "Set-Cookie", "mycookie=foo; HttpOnly"

Pretty simple.

What about cookies you don’t create yourself?

This works great for cookies that you create yourself. But what about those that are created by IIS and ASP, such as the ASPSESSION cookie?

One approach to this is to use the Url Rewrite module in IIS7, and have it add HttpOnly to any outgoing cookies.

This is the solution that is laid out here: http://forums.iis.net/t/1168473.aspx

Steps:

  1. Install the Url Rewrite Module: http://www.iis.net/download/URLRewrite
  2. Modify your web config to contain a rewrite rule:

For classic ASP apps on IIS7, if you don’t already have a web.config file, simply create one in the root directory of your web app.

That’s it. Now your outgoing cookies will be set to HttpOnly.

Verify

We can confirm this by using Fiddler to look at the Response headers:

headers

Notice the HttpOnly keyword in the cookie.

We can also try to access the cookie via some client side Javascript:

alert('mycookie = ' + getCookie('mycookie') );

which yields:

alert_cookie

perfect.

Additional Reading

For more information on HttpOnly cookies, check out:

5 Comments to "Using the URL Rewrite module to set your cookies to HttpOnly"
  1. Colin Hale says:

    What about applying httponly to classic asp headers? Is there a way to do that in a custom header via IIS rather than a code change?

  2. gsherman says:

    @Colin – if you’re using IIS7,you can use the Url Rewrite module, and have it add HttpOnly to any outgoing cookies. This also works for Classic ASP.
    No code changes necessary.

  3. Anonymous says:

    The only problem is that I have IIS 6. Any solutions for that?

  4. gsherman says:

    @anonymous –
    Might depend on your app.
    Is it an asp.net app?
    Scott Hanselman has a post that discusses it:
    http://www.hanselman.com/blog/HttpOnlyCookiesOnASPNET11.aspx

  5. Anonymous says:

    Thanks it really helped

Leave a Comment

International: +1 (512) 610-5400
Toll Free: 1 (800) 684-2055