Вы находитесь на странице: 1из 9

A Beginner's guide for Understanding and

Implementing Cookies in ASP.NET


Rahul Rajat Singh, 16 Jul 2012

This article discuss the basics of cookies. The article talks about what are cookies, why are they
required, how they can be implemented in ASP.NET and what could be the possible/probable
problems while using Cookies.

 Introduction
 Background
1. What are Cookies
2. Type of Cookies
3. Use of Cookies
 Using the code
1. Cookie Attributes
2. Implementing Cookies in ASP.NET
3. Possible Problems with Cookies
4. How Session Cookies work
5. Use of cookies in Forms Authentication
6. Understanding Cookie Munging
 Points of Interest
 History
 References

Introduction
This article discuss the basics of cookies. The article talks about what are cookies, why are they
required, how they can be implemented in ASP.NET and what could be the possible/probable
problems while using Cookies.

Background
What are Cookies

Cookies are the small text files that the Web server writes on the client machine when the client's
browser access their web site. Cookies can be stored in plain text or can be stored in encrypted form.

The first obvious question is why do we need cookies. The answer to that lies in the stateless nature
of web applications. Since web applications are stateless we need some way to manage the state of
the current client request. The state management can be done at server side or client side. Cookies
are actually used to identify the users and facilitate the state management.
Note: There are various other state management techniques. Cookies are client side state
management techniques and there are other client side state management techniques available too.
please refer [1] article to understand all about state management and all types of state management
techniques.

Type of Cookies

Cookies can be classified into various types based on their lifetime behavior and the domain they are
stored for. Major type of cookies are:

1. Session Cookies
2. Persistent Cookies
3. Secure Cookies
4. Third Party Cookies

Session Cookies: This cookie lives in memory of the client computer and its lifetime depends on the
current browser session. If the user closes the browser these cookies are deleted from the client
machine. If the user visits the website again after closing the browser these cookies will not be
available.

Persistent Cookies: Persistent cookies are the cookies that are stored on the secondary storage of
the client machine. These cookies do not depend on the browser session. If the user closes the
browser and then access the website again then these cookies will still be available. The lifetime of
these cookies are specified in cookies itself (as expiration time). The maximum age of such cookies
could be 1 year.

Secure Cookies: These cookies have an attribute for security. there cookies can only be accessed by
the HTTPS connections and not HTTP connections. The reason for having this type of cookie is that
it lessen the chances of cookie stealing/eavesdropping(more on this later in the article)

HttpOnly Cookies: This mode will allow the cookie to be accessed using HTTP or HTTPS requests.
Such cookies will not be accessible by any other methods(JavaScript APIs for instance)

Third Party Cookies: First party cookies are the cookies which set the domain of the cookie same as
the domain or sub-domain of the website that is being browsed. Third Party Cookies on the other
hand are the cookies with domain set to different domain then the website being browsed. These
cookies are mainly used for tracking user browsing patterns and/or finding the Advertisement
recommendations for the user.

Use of Cookies

The main use of Cookies are:


State Management (Session Management)

The state management can be done using cookies. The cookies themselves are very good way to
have client side state management that requires the state to e remembered between website visits.

Along with being client side state management, the cookies are also very useful in maintaining the
sessions on servers. Session being a server side state management technique stores all the state
related data on the server. But the server still need to uniquely identify the client to associate the
correct session data with it. This is facilitated by Cookies.

ASP.NET Roles and Membership and Custom forms authentication also uses cookies for
authentication and authorization. Please see the the following articles for details on
these [3], [2] topics. There is a section at the end of this article which discusses the use of cookies in
session management in details.

Web Page Personalization

Web page personalization can also be achieved using cookies. User can set there personalization
preferences and these preferences can be saved on server. Using cookies we can identify the same
user and then load the personalized version for him.

The User Profiles in ASP.NET, if tracking the anonymous users also uses cookies to track the
anonymous users. More on user personalization can be found here[4]

Tracking User

Cookies are also user to track the user browsing patterns. This is mainly done to identify whether the
user is visiting the site for the first time or is he a returning user. Also This is being done to find the
Ad recommendations for the user.

Using the code


Cookie Attributes

Understanding cookie attributes is important. As the life and behavior of cookies are governed by
the cookie attributes. Let us discuss some important cookie attributes now.

Secure: When this attribute is specified the cookie can only be accessed over HTTP. This reduces the
chances of cookies getting stolen or eavesdropping of cookies.

Domain and Path: These two attributes are to identify the web site and the particular URL of that
website for which this cookie is being set.
HTTPOnly: using this attribute the cookies are forced to be used over HTTP or HTTPS only. This
reduced the chances of cross site scripting because the JavaScript APIs will not be able to access
cookies.

Expires: This attribute specifies whether the cookie is persistent or non persistent. If we don't specify
this attribute the cookie will be non persistent i.e. closing the browser will remove the cookie from
the browser memory. If this attribute is specified then the cookie will be written on the client
machine and will be valid till the time specified in this attribute is reached.

Implementing Cookies in ASP.NET

Let us now see how we can implement cookies using ASP.NET. We will develop a small sample
application which will use cookies to track the user's name and the time of his last visit on this site.
We will use a persistent cookie to remember this information.

Let us start by having a simple page that shows the user information i.e. name and last visit. The
basic algorithm for implementing the desired functionality will be:

1. We will check if the time of last visit is present in the cookies.


2. If not then this is perhaps the first time user is visiting the site.
a. We will show the default texts to him.
b. Save the users visit time in a cookie.
c. If the user chooses to save his name then save his name in a cookie.
3. If the cookie is present
a. Load the data from the cookie
b. Show the time of last visit
c. If his user name is present show it
d. Update the current time as the last visit time in the cookie
e. If the user chooses to save his name then save his name in a cookie.

All the cookies we will create are persistent cookies i.e. we will specify the expiration time for the
cookies. Let us see how the above algorithm can be implemented in code.

protected void Page_Load(object sender, EventArgs e)


{
//let us check if the cookie for username exist or not
if (Request.Cookies["UName"] != null)
{
Label1.Text = Request.Cookies["UName"].Value;
}
else
{
Label1.Text = "Guest";
}

//Let us check if the time of last visit exist or not


if (Request.Cookies["LVisit"] != null)
{
Label2.Text = Request.Cookies["LVisit"].Value;
}
else
{
Label2.Text = "Never";
}

if (IsPostBack == false)
{
// Whenever user visit this page or move away from the page lets write the cookie
// that tracks the last visit time
HttpCookie cookie = new HttpCookie("LVisit");

//Set the cookie value


cookie.Value = DateTime.Now.ToString();

//make it a persistant cookie by setting the expiration time


cookie.Expires = DateTime.Now.AddDays(1);

//Push the cookie to the client computer.


Response.Cookies.Add(cookie);
}
}

protected void Button1_Click(object sender, EventArgs e)


{
HttpCookie cookie = new HttpCookie("UName");

//Set the cookie value


cookie.Value = TextBox1.Text;

//make it a persistant cookie by setting the expiration time


cookie.Expires = DateTime.Now.AddDays(1);

//Push the cookie to the client computer.


Response.Cookies.Add(cookie);
Label1.Text = TextBox1.Text;
}

So let us run the page for the first time.


So this time it is showing us the default text because the cookie containing the data was not present
on the system. Let us now save our name and close the browser. When I open the browser again my
data is shown because it was stored in a cookie on the users computer.

If I want to see the actual cookie file then I can find that in the "C:\Document and
Settings\USERNAME\Cookies" folder. To view these files I have to set the folder options to view
the hidden files and operating system files.
The cookie itself when looked in the internet explorer:

Now we have a basic application with reading and writing of cookies functionality ready. The sample
code simply contains the code for reading and writing and setting the expiration time. Other cookie
attributes can also be set in the similar fashion.

Possible Problems with Cookies

Since cookies data travel over the network between client and server, there are chances that the
cookie can be intercepted in between and someone can use it to mimic our session on the server. In
case of persistent cookies we should never save the sensitive data in cookies as they can be read by
anyone.Another limitation of using cookies is their size. The browsers often limit the size of the
cookie file (4MB in most cases) which is why we should avoid storing large data in cookies.

How Session Cookies work

As we have discussed above the cookies are the also used in maintaining the session information. It
is really necessary to understand how this works. This understanding will definitely be very beneficial
for an ASP.NET developer.

1. User session is created and the data is stored in session variables.


2. A unique session identifier is written in a non persistent cookie.
3. Whenever a request is made to the server the cookie data is read and unique identifier is extracted.
4. This unique identifier is then used to map to user specific data saved on the server memory.
Use of cookies in Forms Authentication

ASP.NET custom forms authentication also uses the same mechanism. It also encrypts the cookie so
that even of the cookie is saved on the disk nobody will be able to access that.

1. Ask the user to enter his login credentials.


2. Generate the user specific encrypted cookie either in persistent or non persistent mode
3. Whenever the authorization is required this cookie is read and checked for authorization for the
user.

In the above method if the user wants to save his login credentials and want to be logged in
between visits then the cookie should be a persistent cookie else it should be a non persistent
cookie.

Note: The details about Forms authentication can be found here: [2]

Understanding Cookie Munging

Now we have seen that the most crucial use of cookies in ASP.NET framework is in tracking sessions
and implementing Forms authentication. Now what if the user has disabled cookies in his browser.

If the user has disabled the cookies then the ASP.NET framework uses the URL to keep track of
session and authentication data. the unique session ID is then put in the urls and used to track the
user session. If the web page contain links i.e. hrefs then the same session ID will also be
associated with all the href links. This process in ASP.NET terminology known as cookie munging.

Points of Interest
What we have seen in this article is the very basic about cookies. We have tried to see why and when
cookies are beneficial and needed. We implemented a small application to set and get cookies. We
also say the how ASP.NET uses cookies internally to manage sessions and user profile information.
This article is written from the perspective of an absolute beginner. I hope this has been informative.

Вам также может понравиться