Search code examples
c#asp.neturl-rewritingweb-config

Use unsecured cookies and secure cookies depending on context


We are currently trying to convert some legacy applications. While in development, we are having a lot of issues with secure cookies. While that is definitely on our to-do list, it is halting work on other functionality. We would like to be able to set cookies in our dev environment so that if we reach the site via HTTP, it uses unsecure cookies, but if they reach the site via HTTPS, it uses secure cookies. We are trying to use IIS Url Rewrite to accomplish this. I mocked this up:

<rewrite>
    <outboundRules>
        <rule name="Enable secure Cookies {ProjectName}" preCondition="Missing Secure Cookies {ProjectName}">
            <match serverVariable="RESPONSE_Set_Cookie" pattern=".*" negate="false" />
            <action type="Rewrite" value="{R:0}; secure" />
            <conditions>
                <add input="{HTTPS}" pattern="^Off$" negate="true"/>
            </conditions>
        </rule>
        <rule name="Enable http only {ProjectName}" preCondition="Missing Http Only {ProjectName}">
            <match serverVariable="RESPONSE_Set_Cookie" pattern=".*" negate="false" />
            <action type="Rewrite" value="{R:0}; HttpOnly" />
            <conditions>
                <add input="{HTTPS}" pattern="^Off$" negate="true"/>
            </conditions>
        </rule>
        <preConditions>
            <preCondition name="Missing Secure Cookies {ProjectName}">
                <add input="{RESPONSE_Set_Cookie}" pattern="." />
                <add input="{RESPONSE_Set_Cookie}" pattern="; secure" negate="true" />
            </preCondition>
            <preCondition name="Missing Http Only {ProjectName}">
                <add input="{RESPONSE_Set_Cookie}" pattern="." />
                <add input="{RESPONSE_Set_Cookie}" pattern="; HttpOnly" negate="true" />
            </preCondition>
        </preConditions>
    </outboundRules>
</rewrite>

I added that to the <system.webServer> tag of every web.config file for every project (I actually replace {ProjectName} with the project's name so that different projects have uniquely named rules and preconditions). Unfortunately, I am still getting secure cookies when hitting the site from HTTP. How do I negate the rule when coming from HTTP?

Alternately, is it possible to remove security and httponly if HTTPS is off?


Solution

  • My rewrite syntax was correct. The issue was that I missed a client-side cookie that was being created as secure from an unsecure context and that was causing the failures. I will leave this question available in case someone else has a similar need for both secure and unsecure cookies in the same site. Very bad practice for prod, but excellent for development!