How can I set the Secure flag on an ASP.NET Session Cookie?

Alex picture Alex · Sep 18, 2009 · Viewed 201.3k times · Source

How can I set the Secure flag on an ASP.NET Session Cookie, so that it will only be transmitted over HTTPS and never over plain HTTP?

Answer

Martin Eden picture Martin Eden · May 31, 2011

In the <system.web> element, add the following element:

<httpCookies requireSSL="true" />

However, if you have a <forms> element in your system.web\authentication block, then this will override the setting in httpCookies, setting it back to the default false.

In that case, you need to add the requireSSL="true" attribute to the forms element as well.

So you will end up with:

<system.web>
    <authentication mode="Forms">
        <forms requireSSL="true">
            <!-- forms content -->
        </forms>
    </authentication>
</system.web>

See here and here for MSDN documentation of these elements.