Welcome to AspAdvice Sign in | Join | Help

A word of warning related to Session variables

I see a lot on forums and newsgroups that Session variables are constantly recommended to pass state between ASP.NET pages. Yes, it is simple mechanism, reliable with out-of-process modes and really nice to customize with the providers. Session is very familiar for developers working with various web technologies (not just Microsoft ones), and one could say that Session is one of the (few) true friends of the web developer.

But have you ever thought that Session variables can also be dangerous if you aren't careful? That's because Session variables are global in users context - the very same feature you usually take advantage of - and if you have small bug or something which allows the same page to be opened twice, you can overwrite variables in manner that you didn't really expect.

Consider this simple ASP.NET page:

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

    protected void Page_Load(object sender, EventArgs e)
    {
        //This type of line (IsPostback check and setting to Session) is already a warning sign!
        if (!Page.IsPostBack)
            Session["demonstrationvalue"] = Guid.NewGuid().ToString();   
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <a href="sessiondemo.aspx" target="_blank">Open this same page to a new window</a><br />
    Session["demonstrationvalue"] = <%=Session["demonstrationvalue"].ToString() %>.<br />
     <asp:Button ID="btnShowWhatsOnSession" runat="server" Text="Update the view." />
    </div>
    </form>
</body>
</html>

That's a simple page. Now follow these steps:

1. Run the page in your VS2005 or VS2008 so that it opens in your favorite browser and shows you something like:

Open this same page to a new window
Session["demonstrationvalue"] = 9cefe013-59b8-4273-abc5-6ef4ae591a67.

2. Click the link which opens the same page in a new window, you'll see that the session variable now has another value, for example
Session["demonstrationvalue"] = a00de96a-0417-48bd-b8df-9ed26f2d955c.

3. Now switch to the browser window you opened in step 1 and click the "Update the View" button, you'll see that page too now shows
Session["demonstrationvalue"] = a00de96a-0417-48bd-b8df-9ed26f2d955c.

Ok, so what? Well, think if your page would do something like that but having temporary ids whatever in session variables. Yeah, if you haven't thought it out, maybe not your fault but having some legacy code given to you by the boss as previous employee just left, that *is* dangerous. And if your page would have logic to update something to database directly based on that session id, you could be in trouble, updating something that you didn't expect that could happen.

I just want to mention that that one of the worst bugs in my early career was caused by missing this type of little thing (not getting all the possible execution paths of the page clear to myself) :-). A page just got bit complicated eventually, and it was legacy code with lousy structure - which I got for modification - , which made it really, really difficult to spot. Nevertheless, it was 100% my fault, as I should have noticed it (well, I *really* should have done the full rewrite of the application instead of letting it be as it was, but that's another story...).

Now, I hope you don't make the same mistake as I did by then.

Sponsor
Published Saturday, May 10, 2008 12:18 AM by joteke
Filed under: , ,

Comments

# re: A word of warning related to Session variables

Thanks .. Actually there is many things that can cause the page_load to get called many times with IsPotback=false (Http Get), like AutoWireUp events issues, or the VS 2003 Bugs ,which some times lets page_Load to handle the Page and its Base like this: protected sub Page_load(...)Handles Page.Load,MyBase.Load And about using the sessionId in a DataBase transaction , i think this should be avoided , I'm not sure if its helpful to store the SessionID in the DataBase , even for Audit trails Requirements , why someone would needs to use the SessionId ? Thanks
Friday, May 09, 2008 7:02 PM by Anas Ghanem

# re: A word of warning related to Session variables

Hi,

my point wasn't exactly the Page_Load, I meant that code like this is sign that more global state is used, than what is needed. The actual point was that session variables combined with pages which can be opened in multiple windows can be dangerous. If your page cannot be opened in multiple windows so that session data (user-global data) isn't "switched".

Of course this all is related to what is kept in those variables. If you pick an id from querystring and place that to viewstate, and use further to instantiate objects, you're a bit more safe.

With SessionID's I didn't mean the SessionID generated by ASP.NET, but some relevant IDs you have for data in your database, for example Order id which you keep in ASP.NET's session state. Do you need to kee it there, is the question and answers that are you vulnerable to this kind of misthought (when designing the page flow).

Saturday, May 10, 2008 4:18 AM by joteke
New Comments to this post are disabled