Click here to Skip to main content
Email Password   helpLost your password?

Introduction

This HTTP module allows cookies to be encrypted/decrypted without any change to the Web application making use of the cookies. It effectively bolts on cookie encryption to .NET applications that may not originally have included it.

Using the Code

The solution contains two projects:

  1. CookieEncryptionModule - This is the HTTP module class library that does the actual work.
  2. CookieEncryptionTestWeb - This is a Web project that has been "wired up" to use the HTTP module.

Using the module is as simple as dropping the CookieEncryptionModule.dll file into the Web application bin folder and adding a reference to the httpModules section in the web.config file (see test project). There are various web.config settings (optional) that control how the module handles cookies:

If these are not specified, then the application defaults to encrypting all cookies and removing unencrypted cookies from the request.

Using the Test Website

Since the encryption and decryption of cookies is transparent to the application, you need to look at the cookies directly either through the browser's "View Files" (Internet Explorer) or "Show Cookies" (Firefox) option or by using a tool such as Fiddler 2 Web proxy or the Internet Explorer Developer Toolbar. As an example, to see the way unencrypted cookies are handled:

  1. Open the solution, set CookieEncryptionTestWeb as the startup project and CookieEncryptionTester.aspx as the start page.
  2. Remove TestCookie2 and the separator (|) from the CookieEncryptionModule_CookieList value in the web.config and save the change.
  3. Delete any previous TestCookie values from your browser cache and run the project. The test Web page should show No Cookie for all 4 values as this is populated from cookies sent with the request.
  4. Check the cookies now stored on disk and you should see an unencrypted TestCookie2 and an encrypted TestCookie4. There should be no entry for TestCookie1 or 3 as these are session cookies.
  5. Reverse the change made to the web.config in step 2 so that TestCookie2 is marked as a cookie that requires encryption. Press the Submit button on the test Web page.
  6. Check the cookies now stored on disk and you should see that TestCookie2 is encrypted and has an expiry date 1 year in the future (as specified by the web.config value for CookieEncryptionModule_UnencryptedCookiePolicy).
  7. Remove TestCookie2 and the separator (as step 2) and press the Submit button.
  8. The Web page should now show the encrypted value of TestCookie2 as it is no longer marked as an encrypted cookie.

Points of Interest

I have attempted to ensure that the module defaults to its most secure settings (all cookies encrypted, unencrypted cookies removed from the request) if there are any problems or if the web.config doesn't contain valid settings.

I opted to use the built-in FormsAuthenticationTicket to handle the encryption. This was on the basis that since it is used for forms authentication, it is already optimised for use in this process. However, there should be no problem with replacing this with a custom encryption handler.

There is a hard-coded list (NeverProcessTheseCookies) of cookies that should never be touched. This contains the session cookie by default. If your application uses forms authentication and you want the web.config to specify cookies to be encrypted (rather than ignored), then add the authentication cookie name to this list. If, in the web.config, you are specifying cookies to be ignored then you can add the forms authentication cookie there.

The Value property that is displayed appears to be generated by combining the key/value pairs in the Values collection. If you set the Value property directly, e.g. MyCookie.Value="Test"; this creates a new NameValueCollection with a pair (null, "Test") at position zero. The HasKeys property is only set to true if the Values collection contains non-null keys.

History

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
GeneralProblem with cookie keys
Ryan Salt
6:10 19 Jun '09  
When this module is enabled, if I read a cookie back into an application, the HasKeys value is always set to False, so I cannot read cookie key/value pairs from the values string. if I disable the cookieencryption module in web.config, everything works as expected.
GeneralRe: Problem with cookie keys
Ryan Salt
7:14 19 Jun '09  
I fixed my problem by changing the Action.Decrypt code below in CookieEncryptionModule.cs to check the decrypted value string for "&" characters and then it splits the string into key/value pairs, adds them to a NameValueCollection and adds that collection to the cookie.

case Action.Decrypt:
try {
CookieTicket = FormsAuthentication.Decrypt(cookieToHandle.Value);
if (CookieTicket.UserData.Contains("&"))
{

NameValueCollection myValues = new NameValueCollection();
string[] aryStrings = CookieTicket.UserData.Split(new char[] {'&'});
string[] nameAndValue;
foreach (string s in aryStrings)
{
nameAndValue = s.Split(new char[] {'='});
myValues.Add(nameAndValue[0], nameAndValue[1]);
}
cookieToHandle.Values.Add(myValues);
}
else {
cookieToHandle.Value = CookieTicket.UserData;
}


}

GeneralRe: Problem with cookie keys [modified]
Phil 101
6:40 4 Jul '09  
Thanks for pointing this out - good to know someone's actually found it useful! I've submitted an update today (both the module and the test project).

I've added

private readonly char[] CookieKeyValueSeparators = new char[]{'&', '='};
to the initial field declarations and modified HandleCookie as follows:

case Action.Decrypt:
try {
CookieTicket = FormsAuthentication.Decrypt(cookieToHandle.Value);

// Separate the key/value pairs so that they can be added to the cookie's Values collection
string[] KeyValuePairs = CookieTicket.UserData.Split(CookieKeyValueSeparators);

// Need to clear the encrypted contents from the cookie
cookieToHandle.Values.Clear();

// It is possible for the first cookie part to have a null key. In this case there
// will be an odd number of key/value parts in the array
int FirstPairIndex =0;

if(KeyValuePairs.Length % 2 == 1)
{
cookieToHandle.Value = KeyValuePairs[0];
FirstPairIndex = 1;
}

for(int CurrentKeyIndex=FirstPairIndex; CurrentKeyIndex<KeyValuePairs.Length; CurrentKeyIndex+=2)
{
cookieToHandle.Values.Add(KeyValuePairs[CurrentKeyIndex], KeyValuePairs[CurrentKeyIndex+1]);
}

}

The Value property that is displayed appears to be generated by combining the key/value pairs in the Values collection. If you set the Value property directly, e.g. MyCookie.Value="Test";, this creates a new NameValueCollection with a pair (null, "Test") at position zero (BTW - your code won't handle this situation). The HasKeys property is only set to true if the Values collection contains non-null keys.

Since you're using .NET 2+ you may want to look at modifying the web.config CookieEncryptionModule_UnencryptedCookiePolicy value to represent a TimeSpan and using DateTime.TryParse in the UnencryptedCookiePolicy. If you haven't already done so then you should take a look at Richard Deeming's post regarding the session cookie name under .NET 2+.

modified on Saturday, July 4, 2009 12:24 PM

Generalview cookies
vbytesdc
15:07 5 May '09  
in vs 2008 debugging. how can i view cookies on my computer. not through code?
GeneralRe: view cookies
Phil 101
20:05 7 May '09  
It depends on the browser you are using. Do a web search for <browser name> view cookies - e.g. Firefox view cookies .
GeneralGreat article
chrislively
8:15 30 May '08  
Easy to implement code; works like a charm.

To utilize under IIS 7 be sure to add the module to the system.webserver modules section of the web.config.
NewsNote: Problems Uploading Updated Code [modified] - Problem Resolved
Phil 101
11:25 10 Dec '07  
I am having problems getting the updated code to upload and available for download. The version currently linked is the original version.

21st Dec. The correct code is now available for download.
modified on Friday, December 21, 2007 6:14:19 AM

GeneralSessionID cookie
Richard Deeming
7:56 10 Dec '07  
In ASP.NET 2.0, the name of the session ID cookie can be changed via the web.config file, so it's not a good idea to hard-code it as "ASP.NET_SessionId".

To read the cookie name from the config file, you can use something like this:

using System.Web.Configuration;
...
SessionStateSection section = (SessionStateSection)WebConfigurationManager.GetSection("system.web/sessionState");
if (HttpCookieMode.UseUri == section.Cookieless) return null;
return section.CookieName;



"These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

QuestionUsing the test web site - Section Added
Phil 101
9:00 9 Dec '07  
Wimmo / Jeffrey

Is this the sort of thing you were looking for?

Cheers
Phil
GeneralI Second Wimmo
Jeffrey Walton
0:56 5 Dec '07  
Usage is basically missing.
GeneralNice but
Wimmo
5:46 1 Dec '07  
Nice article but can you write out more about your code and how you came to your approach?

Cheers WimHmmm


Last Updated 5 Jul 2009 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010