Cookieless Session ASP.NET

Cookie–>Cookies are usually small text files, given ID tags that are stored on user computer’s browser directory or program data subfolders. Cookies are created when use your browser to visit a website that uses cookies to keep track of movements within the site. The website stores a corresponding file(with same ID tag)to the one they set in browser and in this file they can track and keep information on movements within the site and any information may have voluntarily given while visiting the website, such as email address.

There are two types of cookies:

Session cookies – these are temporary cookie files, which are erased when close browser. When restart the browser and go back to the site that created the cookie, the website will not recognize. We will have to log back in (if login is required) or select preferences/themes again if the site uses these features. A new session cookie will be generated, which will store browsing information and will be active until leave the site and close your browser.

Persistent cookies – these files stay in one of browser’s subfolders until delete them manually or browser deletes them based on the duration period contained within the persistent cookie’s file

Cookieless ASP.NET

Session state gives the ability to persist a piece of information about a user for the duration of time the user interacts with the application. The user-specific information is generally preserved for a 20-minute period that is renewed each time the user comes back to the site.

The first time the user connects to the site a brand new session state is created in the form of a block of memory to hold data, plus an ID to uniquely link it to the current user. On the next request, the user is expected to present the session ID so that the session state can be retrieved and properly restored. The session ID is an alphanumeric string that ASP and ASP.NET generate in total autonomy. How can the user manage it and make sure it is wrapped up with each subsequent request?

So cookies store the ID of the session and browsers transparently move their contents back and forth between the Web server and the local user’s machine. When a cookie-enabled browser receives a response packet, it looks for attached cookies and stores their content to a text file in a particular folder in the local Windows directory. The cookie also contains information about the site of origin. Next, when the browser sends a request to the site, it looks in the cookies folder for a cookie that originated from that domain. If found, the cookie is automatically attached to the outgoing packet. The cookie hits the server application where it is detected, extracted, and processed.

In the end, cookies make Web sites much easier to navigate because they provide the illusion of continuity on top of a user’s experience that necessarily spans over multiple requests.

cookies are not programs and therefore can’t collect any information on their own, let alone any personal information about users. More simply, a cookie is a piece of text that a Web site can park on a user’s machine to be retrieved and reused later. The information stored consists of harmless name-value pairs.

Enter Cookieless Sessions

In ASP.NET, the necessary session-to-user link may optionally be established without using cookies. Interestingly enough, you don’t have to change anything in your ASP.NET application to enable cookieless sessions, except the following configuration setting.

<sessionState cookieless=”true” />

The session ID is embedded in the URL and there’s no need to persist it anywhere. Well, not exactly.. Consider the following scenario.

You visit a page and get assigned a session ID. Next, you clear the address bar of the same browser instance, go to another application and work. Then, you retype the URL of the previous application and, guess what, retrieve your session values as you get in.

If you use cookieless sessions, in your second access to the application you’re assigned a different session ID and lose all of your previous state. This is a typical side effect of cookieless sessions. To understand why, let’s delve deep into the implementation of cookieless sessions.

Let’s review the pros and cons of cookieless sessions.

Thumbs Up

In ASP.NET, session management and forms authentication are the only two system features that use cookies under the hood. With cookieless sessions, we can now deploy stateful applications that work regardless of the user’s preferences about cookies. As of ASP.NET 1.x, though, cookies are still required to implement forms authentication. The good news is that in ASP.NET 2.0 forms authentication can optionally work in a cookieless fashion.

Thumbs Down

Let’s look at security from another perspective. We have heard of session hijacking?

Using cookieless sessions also raises issues with links. For example, we can’t have absolute, fully qualified links in ASP.NET pages. If we do this, each request that originates from that hyperlink will be considered as part of a new session. Cookieless sessions require that we always use relative URLs, like in ASP.NET postbacks. we can use a fully qualified URL only if we can embed the session ID in it. But how can we do that, since session IDs are generated at run time?

The following code breaks the session:

<a runat="server" href="/test/page.aspx">Click</a>

To use absolute URLs, resort to a little trick that uses the ApplyAppPathModifier method on the HttpResponse class:

<a runat="server"
    href=<% =Response.ApplyAppPathModifier("/test/page.aspx")%> >Click</a>

The ApplyAppPathModifier method takes a string representing a URL and returns an absolute URL that embeds session information. For example, this trick is especially useful in situations in which we need to redirect from a HTTP page to an HTTPS page. Finally, be conscious that every time type a path to a site from within the same browser we are going to lose state with cookieless sessions. As a further warning, be aware that cookieless sessions can be problematic with mobile applications if the device can’t handle the specially formatted URL.

In web.config following settings should do.it is related to authentication forms mode and cookieless session state.

<sessionState cookieless=”true”

                            />                   

                        <authentication mode=”Forms”>                    

                        <forms loginUrl=”Login.aspx” protection=”All” timeout=”30″

                            name=”.ASPXAUTH” path=”/”

                            requireSSL=”false” slidingExpiration=”true”

                            defaultUrl=”default.aspx”

                            cookieless=”UseUri” enableCrossAppRedirects=”true”/>                  

                        </authentication>

->Create HttpModule to rewrite your incoming URL for enabling cross domain posts

using System;

using System.Collections.Specialized;

using System.Web;

using System.Web.SessionState;

using System.IO;

using System.Text;

 

namespace CustomModule

{

public sealed class CookielessPostFixModule : IHttpModule

{

public void Init (HttpApplication application)

{

application.EndRequest += new

EventHandler(this.Application_EndRequest);

}

private string ConstructPostRedirection(HttpRequest req,

HttpResponse res)

{

StringBuilder build = new StringBuilder();

build.Append(

“<html>n<body>n<form name=’Redirect’ method=’post’ action='”);

build.Append(res.ApplyAppPathModifier(req.Url.PathAndQuery));

build.Append(“‘ id=’Redirect’ >”);

foreach (object obj in req.Form)

{

build.Append(string.Format(

“n<input type=’hidden’ name='{0}’ value = ‘{1}’>”,

(string)obj,req.Form[(string)obj]));

}

build.Append(

“n<noscript><h2>Object moved <input type=’submit’

value=’here’></h2>

</noscript>”);

build.Append(@”</form>

<script language=”‘javascript'”>

<!–

document.Redirect.submit();

// –>

</script>

“);

build.Append(“</body></html>”);

return build.ToString();

}

private bool IsSessionAcquired

{

get

{

return (HttpContext.Current.Items[“AspCookielessSession”]!=null &&

HttpContext.Current.Items[“AspCookielessSession”].ToString().Length>0);

}

}

private string ConstructPathAndQuery(string[] segments)

{

StringBuilder build = new StringBuilder();

 

for (int i=0;i<segments.Length;i++)

{

if (!segments[i].StartsWith(“(“)

&& !segments[i].EndsWith(“)”))

build.Append(segments[i]);

}

return build.ToString();

}

private bool IsCallingSelf(Uri referer,Uri newpage)

{

if(referer==null || newpage==null)

return false;

string refpathandquery = ConstructPathAndQuery(

referer.Segments);

return refpathandquery == newpage.PathAndQuery;

}

private bool ShouldRedirect

{

get

{

HttpRequest req = HttpContext.Current.Request;

 

return (!IsSessionAcquired

&& req.RequestType.ToUpper() == “POST”

&& !IsCallingSelf(req.UrlReferrer,req.Url));

}

}

private void Application_EndRequest(Object source, EventArgs e)

{

HttpRequest req = HttpContext.Current.Request;

HttpResponse res = HttpContext.Current.Response;

if (!ShouldRedirect) return;

res.ClearContent();

res.ClearHeaders();

res.Output.Flush();

char[] chr = ConstructPostRedirection(req,res).ToCharArray();

res.Write(chr,0,chr.Length);

}

public void Dispose()

{}

}

}

For the above to be effective, make the below change to web config:

<httpModules>

<add type=”CookielessPostFixModule, OurModule”

name=”CookielessPostFixModule” />

</httpModules>

  1 comment for “Cookieless Session ASP.NET

Leave a Reply