title: Making server cookies secure
body: <p>I've been trying to figure out how to set the secure flag on all the server cookies for our website. We're running .NET 4.5. I tried adding <code>&lt;httpCookies requireSSL="true" /&gt;</code> to the web.config file. I tried adding <code>&lt;authentication&gt;&lt;forms requireSSL="true" /&gt;&lt;/authentication&gt;</code>. I tried setting the secure flag in code. Nothing had any effect. Adding the following c# function to Global.asax.cs was supposed to work, but didn't:</p>
  
  <pre><code>    protected void Application_EndRequest()
      {
          string authCookie = FormsAuthentication.FormsCookieName;
  
          foreach (string sCookie in Response.Cookies)
          {
              if (sCookie.Equals(authCookie))
              {
                  // Set the cookie to be secure. Browsers will send the cookie
                  // only to pages requested with https
                  var httpCookie = Response.Cookies[sCookie];
                  if (httpCookie != null) httpCookie.Secure = true;
              }
  
      }
  </code></pre>
  
  <p>It finally started working after I got rid of the "if (sCookie.Equals(authCookie))..." statement. So this is the working version:</p>
  
  <pre><code>    protected void Application_EndRequest()
      {
          string authCookie = FormsAuthentication.FormsCookieName;
  
          foreach (string sCookie in Response.Cookies)
          {
              // Set the cookie to be secure. Browsers will send the cookie
              // only to pages requested with https
              var httpCookie = Response.Cookies[sCookie];
              if (httpCookie != null) httpCookie.Secure = true;
          }
      }
  </code></pre>
  
  <p>I have several questions. First, what is the logic behind putting this in the Application_EndRequest method? Second, why did I have to get rid of the sCookie.Equals(authCookie)) part? Finally, has anyone found a more elegant solution? Thanks.</p>