Sunday, May 22, 2011

CFCookie vs CFHeader for Session Cookies

A lot of times we re-write ColdFusion session cookies to add some additional flags. Flags like Secure, HttpOnly which were not present in the earlier releases. HttpOnly support was added in ColdFusion 9.0.1.

When one doesn't use J2EE session management, ColdFusion managed sessions are used. In This two cookies, CFID and CFTOKEN are set. There are additional authentication cookies added when is used. By default till CF9.0 they were not marked as secure and HttpOnly. With CF9.0.1, support for HttpOnly was added. 

Today, I am going to talk about, how to set these additional flags on these cookies. This is talked about a lot of times, but I would like to add my 2 cents to this. To add these additional flags (these flags provide additional security), one can use CFCookie or CFHeader. And here is the difference which I thought was worth mentioning.

With, CFCookie, the cookie name is always converted to Upper Case, and Value is encoded. This is not a problem for CFID or CFTOKEN but might not work with Authorization cookie, or even if you want to set some flags for JSessionID cookie.

CFHeader on the other hand will be handy to set any of these flags. So the preferred choice should be CFHeader while doing this.

For setting these cookie at your own, you must set sessionmanagement = true, clientclientcookie = false in Application.cfc/cfm as appropriate. Here is an example of an application with application name "test"

Using CFCookie

<cfif NOT StructKeyExists( cookie,"CFID" ) OR ( cookie.CFID NEQ session.CFID )>

      <!---using the CFID and CFTOKEN cookies again with same values but making them secure--->
      <cfcookie name="CFID" value="#session.CFID#" secure="true" httponly="true">


      <cfcookie name="CFTOKEN" value="#session.CFTOKEN#" secure="true" httponly="true">
</cfif>

<cfcookie name="CFAUTHORIZATION_test" value="#cookie.CFAUTHORIZATION_test#"  secure="true">

Note: cfccokie tag for Authorization cookie, here will create another cookie with same name but in different case, rather than updating the original one.




Using CFHeader


<cfif NOT StructKeyExists( cookie,"CFID" ) OR ( cookie.CFID NEQ session.CFID )>

      <!---using the CFID and CFTOKEN cookies again with same values but making them secure--->
      <cfheader name="Set-Cookie" value="CFID=#session.CFID#;SECURE;HttpOnly;"/>
      <cfheader name="Set-Cookie" value="CFTOKEN=#session.CFTOKEN#;SECURE;HttpOnly;"/>
</cfif>
<!---cfheader tag will update the original cookie generated by cflogin and will make it secure--->
<cfheader name="Set-Cookie" value="CFAUTHORIZATION_test=#cookie.CFAUTHORIZATION_test#;SECURE;HttpOnly;"/>



Hope this was helpful.


No comments:

Post a Comment

You can subscribe to the comments by licking on "Subscribe by email".