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?
问题:
回答1:
There are two ways, one httpCookies
element in web.config
allows you to turn on requireSSL
which only transmit all cookies including session in SSL only and also inside forms authentication, but if you turn on SSL on httpcookies you must also turn it on inside forms configuration too.
Edit for clarity:
Put this in <system.web>
<httpCookies requireSSL="true" />
回答2:
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.
回答3:
Things get messy quickly if you are talking about checked-in code in an enterprise environment. We've found that the best approach is to have the web.Release.config contain the following:
<system.web>
<compilation xdt:Transform="RemoveAttributes(debug)" />
<authentication>
<forms xdt:Transform="Replace" timeout="20" requireSSL="true" />
</authentication>
</system.web>
That way, developers are not affected (running in Debug), and only servers that get Release builds are requiring cookies to be SSL.