REQUEST A DEMO

Using the URL Rewrite module to set your cookies to HttpOnly

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:

7 Comments

  • Colin Hale

    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?

  • gsherman

    @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.

  • Anonymous

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

  • gsherman

    @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

  • Anonymous

    Thanks it really helped

  • George

    Hi,
    read Your example and used is it to append ‘SameSite=Strict’ to response cookies.
    After setting rule – checked that preconditions return true.
    Site returns OK (status 200) but cookies are not modified. Also there are no errors in logs.
    Any idea for the reason?

  • ADD COMMENT

    Your email address will not be published.