Asp.net Sessions Getting Crossed / Mixed Up - asp.net

Few weeks ago we had one of our customers contacting us saying that sometimes when he creates an activity it gets created under someone else's name!
We did some troubleshooting and couldn't find anything. We asked the user to contact us the next time he was experiencing these issues. He did contact us and we were able to do a gotomeeting with him and see the issue with our own eyes.
It was not only the activities, he was recognized as someone else in the application. He had access to everything that other person should had access to. That was when we realized we are having a session mixed up issue.
A little bit about our code:
Like any other application we have a simple login page that user enter email and password and we authenticate them against our database and if they are valid we call FormsAuthentication.SetAuthCookie() to save current user id in the cookie and we let him in.
BL.User currentUser = BL.User.Authenticate(txtUsername.Text, txtPassword.Text);
if (currentUser != null)
{
this.Session["NumberOfLoginTried"] = "0";
FormsAuthentication.SetAuthCookie(currentUser.UserID.ToString(), chRememberMe.Checked);
Response.Redirect(FormsAuthentication.GetRedirectUrl(currentUser.UserID.ToString(), false));
}
We also use the following piece of code to get logged-in user id (current user) in our application.
public static int GetCurrentUserID()
{
int userID = -1;
int.TryParse(HttpContext.Current.User.Identity.Name, out userID);
return userID;
}
And yes we did our homework and googled around and have seen the following two links:
http://lionsden.co.il/codeden/?p=446
ASP.NET Session Mix-up using StateServer (SCARY!)
We have disabled kernel-mode caching and user-mode caching for .aspx and .ascx files and this is still happening.
P.S- The app is running on Windows 2008 R2 with IIS 7.5. And we are NOT using cookieless session.

We have just had a very similar problem, which occured at random, seemingly un-reproducibly.
The problem turned out to be ASP.NETs Page caching mechanism - in our case the <%# OutputCache tag in particular.
There was a line we had used
<%# OutputCache NoStore="true" Duration="1" %> that basically meant if two users accessed the same page within 1 second of each other they would see the same page (including the logged in username of the other user). So if they refreshed said page, they got the correct information.
In our case, changing said line to
<%# OutputCache NoStore="true" Duration="1" VaryByParam="*" %>, disabling kernel caching in IIS as in this link (http://lionsden.co.il/codeden/?p=446)
and adding the following lines to the Page_Load event of the page in question:
Response.CacheControl = "private";
Response.ExpiresAbsolute = DateTime.Now.AddDays(-1d);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Seems to have solved the problem for us. Hopefully this helps someone else with a similar issue.

We had the same problem and it was caused by the <clientCache/> setting in IIS, which by default fails to add the Cache-Control: private HTTP header. The lack of this header meant that our Forms Authentication cookies were being cached by downstream proxy servers! So when our site got busy, all of a sudden a load of users would suddenly get logged in as the wrong user! Nightmare.

if removing the <%# OutputCache NoStore="true" Duration="1" VaryByParam="*" at all (in all ascx files being in the line from Master to aspx too !!!) prevented from cross-sessions. having only one ascx with outputcache directive loaded, cross-sessions occured.
It did not matter in my case if using sessionstat InProc ore StateServer, if having cookieless or cookie sessions.

We had the same problem at the company I work at. We also realized that it was caused by output caching, which resulted in sending someone else's SessionId to the wrong person.
We have now added the following <caching> element to our web.config.
<configuration>
[...]
<system.webServer>
[...]
<caching enabled="false" enableKernelCache="false">
</caching>
</system.webServer>
[..]
</configuration>
We can't guarantee this will solve it, because the problem is almost impossible to reproduce, but based on our research, this should solve it.
Strangely, the link to a Microsoft article describing this problem that can be found on the internet gives some general page as if the page has been deleted.
But there is this Microsoft article that seems to describe the same issue voor IIS 6:
An ASP.NET page is stored in the HTTP.sys kernel cache in IIS 6.0 when the ASP.NET page generates an HTTP header that contains a Set-Cookie response
Which describes the symptom as:
Consider the following scenario. A Microsoft ASP.NET page contains the <%# OutputCache %> directive. Additionally, the ASP.NET page generates an HTTP header that contains a Set-Cookie response. In this scenario, the ASP.NET page is stored in the HTTP protocol stack (HTTP.sys) kernel cache in Microsoft Internet Information Services (IIS) 6.0. Therefore, multiple users who access the same page may receive identical cookies.
Update
I found this really good article at Microsoft Premier Developer blog that explains a lot:
ASP.Net Session Swapping – Why it happens and what can be done about it?

Because you all disabled kernel-mode caching, I like to point out some other thinks.
1) To correctly use the HttpContext.Current.User.Identity.Name, you first need to verify that your user is logedin by using the User.Identity.IsAuthenticated
2) in this point Session.Add("CurrentUser", currentUser); what are you actual try to save ?
Now I think that is the problem is on cache. The pages are stored somewhere in between your users and the one mix up with the other. Some of the headers that you can use to your page to avoid the cache on the middle proxy computers.
Response.Cache.SetExpires(DateTime.UtcNow.AddYears(-2));
Response.Cache.SetNoStore();
Response.Cache.SetValidUntilExpires(false);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ExpiresAbsolute = DateTime.Now.Subtract(new TimeSpan(1, 0, 0, 0));
Response.Expires = 0;
Response.CacheControl = "no-cache";
Response.AppendHeader("Pragma", "no-cache");
Also I say that if your pages have data that you do not wish to share among your user you need to use Secure HTTPS pages, and set your cookies to be available only on secure pages by adding <httpCookies httpOnlyCookies="true" requireSSL="true" /> on web.config
Also, check if you save your session on SQL server that you scheduled run the clean up routing every 1 minute.
To been able to find some more information I suggest to store some hidden text on the pages, eg the date-time of the rendered, maybe a the last 4 digit of the userID, and what else you may thing that can help you see if the page come from a cache or not.

Since this seems to fall into the extremely arcane problem territory, maybe it's time for a leap.
You could stop using the ASP.NET session to store your identifiers altogether.
You have a bunch of options of where you could stick this information instead. You could choose to encrypt it into the Forms Authentication ticket's UserData property (I've done this before in production, it works great for storing a key(s), csv of roles, or even small json objects). Past the forms auth ticket, you could write the information directly as your own cookie. You could also bypass cookies altogether.
If you choose to bypass the cookies, you're basically entering into similar territory of the cookieless ASP.NET sessions. You have a couple of options, you could make the user identifier be apart of every single url as a query parameter. Another option would be to create a HttpModule that would add a hidden form input into every page response that contains the logged in user's identifier.
If you go down the cookieless path absolutely make sure it's not possible to use your site as HTTP and every single request is HTTPS. Even more especially if you use the query parameter method.

If you checked that output caching is not the problem
There is already on answer from me here, but as it turned out my other solution (disabling the output cache) did not really solve our problem for us.
Since in the question it is stated that caching is turned off, the only other possible (AFAIK) bug that can produce this is what turned out to be the real culprit in our case: we use a private variable in a ActionFilterAttribute.
And because these are cached, storing private/personal data from a user in this way can also lead to session mix-up!
This answer describes what our problem was and how to fix it:
https://stackoverflow.com/a/8937793/1864395
Also, I think it's good to mention that we were able to reproduce the problem by running Apache JMeter with a scenario for several users at the same time. It's a really nice tool (although not really user friendly/intuitive) used for (among other things) stress-testing. It's probably the only way to diagnose session mix-ups!

Related

How to detect if SessionState has expired?

What would be the best way to detect if the SessionState has died in order to send the user to a "Session Expired" page? I've successfully configured the app (in Web.config) to do this when the authentication cookie is gone (there's a setting for that), but so far I haven't found an effective way to do something similar when the SessionState is gone. The app in question holds some data in the Session, and should present the user with a "Session Expired - Please login again" page if any of them is gone.
So far, the only option I can think of doing it in each of the places I access Session, but this is obviously a less than optimal solution.
I remember a similar question. Actually, you don't have many opportunities.
I mean, you can't redirect a user to a page when server fires the SessionEnd event, that you can handle in Global.asax.
However, if you play with the Session object from inside the page you can do something useful... For example, save the session ID in the page's context, or in a hidden field. When you postback, compare the saved ID with your Session ID. If they differ, a new session started, meaning that the old one expired.
Now it's time to redirect the user :)
Hope to have been of help.
Yeah it's tough. :)
There is no real simple/definitive way to do it.
One option is stick a guid/idenfitier in the Session[] collection during Session_Start (global.asax), and then check for this value in Page_Load of your base page (e.g master).
Another option is to check the actual ASPX cookie:
HttpCookie sessionCookie = Request.Cookies["ASP.NET_SessionId"];
If it's null, the session is over.
Why not include the session check on the masterpage? Any of your session variables will return null if the session has expired. So on page_load you can check any of them and carry out the appropriate action i.e. Response.Redirect. However you say in the Web.Config you can check when the authentication cookie is gone, so can you not carry out an action on this?
Another method would be to use a HTTP Module which would intercept each request and decide what to do with it. This would be better than my first method and it'll occur prior to any page processing.
When the client logs in, you give him a session flag, like notexpired and set it to 1.
Then you write a web-module, which on every http request checks if notexired = 1.
If that check throws an exception or is 0, you can deny access or redirect to an error page.
or you can renew the session from the database, should you save sessions into the database.
Incidentially, this also works with AJAX handlers, unlike base-page class hacks.
there are lots of examples on internet to solve your problem (it's quite common)
have a look at
http://geekswithblogs.net/shahed/archive/2007/09/05/115173.aspx
Another way is check the repository sessions values are maintained.
In my case we have a hashtable and we log the session ID then every time we need that session we checked if the value is still there..
That a centralized way to keep your app about the status of your session
Hope this helps/
Check out for this property at the Page_Load event of your desired page:
Dim sessionExpired as Boolean = Context.Session.IsNewSession
For more information, please visit this link.
Notice the "liveliness" of the session state is set by default to 20 min, but this can be easily changed in the web.config of the application with the timeout property:
<system.web>
<!--Set default timeout for session variables (default is 20 minutes, but was changed to 30 minutes-->
<sessionState mode="InProc" cookieless="false" timeout="30" />
</system.web>
Also, please check out at MSDN for the other properties mode and cookieles. It can help to extend the validity of your current business situation.

ASP.NET: Session.SessionID changes between requests

Why does the property SessionID on the Session-object in an ASP.NET-page change between requests?
I have a page like this:
...
<div>
SessionID: <%= SessionID %>
</div>
...
And the output keeps changing every time I hit F5, independent of browser.
This is the reason
When using cookie-based session state, ASP.NET does not allocate storage for session data until the Session object is used. As a result, a new session ID is generated for each page request until the session object is accessed. If your application requires a static session ID for the entire session, you can either implement the Session_Start method in the application's Global.asax file and store data in the Session object to fix the session ID, or you can use code in another part of your application to explicitly store data in the Session object.
http://msdn.microsoft.com/en-us/library/system.web.sessionstate.httpsessionstate.sessionid.aspx
So basically, unless you access your session object on the backend, a new sessionId will be generated with each request
EDIT
This code must be added on the file Global.asax. It adds an entry to the Session object so you fix the session until it expires.
protected void Session_Start(Object sender, EventArgs e)
{
Session["init"] = 0;
}
There is another, more insidious reason, why this may occur even when the Session object has been initialized as demonstrated by Cladudio.
In the Web.config, if there is an <httpCookies> entry that is set to requireSSL="true" but you are not actually using HTTPS: for a specific request, then the session cookie is not sent (or maybe not returned, I'm not sure which) which means that you end up with a brand new session for each request.
I found this one the hard way, spending several hours going back and forth between several commits in my source control, until I found what specific change had broken my application.
In my case I figured out that the session cookie had a domain that included www. prefix, while I was requesting page with no www..
Adding www. to the URL immediately fixed the problem. Later I changed cookie's domain to be set to .mysite.com instead of www.mysite.com.
my problem was that we had this set in web.config
<httpCookies httpOnlyCookies="true" requireSSL="true" />
this means that when debugging in non-SSL (the default), the auth cookie would not get sent back to the server. this would mean that the server would send a new auth cookie (with a new session) for every request back to the client.
the fix is to either set requiressl to false in web.config and true in web.release.config or turn on SSL while debugging:
Using Neville's answer (deleting requireSSL = true, in web.config) and slightly modifying Joel Etherton's code, here is the code that should handle a site that runs in both SSL mode and non SSL mode, depending on the user and the page (I am jumping back into code and haven't tested it on SSL yet, but expect it should work - will be too busy later to get back to this, so here it is:
if (HttpContext.Current.Response.Cookies.Count > 0)
{
foreach (string s in HttpContext.Current.Response.Cookies.AllKeys)
{
if (s == FormsAuthentication.FormsCookieName || s.ToLower() == "asp.net_sessionid")
{
HttpContext.Current.Response.Cookies[s].Secure = HttpContext.Current.Request.IsSecureConnection;
}
}
}
Another possibility that causes the SessionID to change between requests, even when Session_OnStart is defined and/or a Session has been initialized, is that the URL hostname contains an invalid character (such as an underscore). I believe this is IE specific (not verified), but if your URL is, say, http://server_name/app, then IE will block all cookies and your session information will not be accessible between requests.
In fact, each request will spin up a separate session on the server, so if your page contains multiple images, script tags, etc., then each of those GET requests will result in a different session on the server.
Further information: http://support.microsoft.com/kb/316112
My issue was with a Microsoft MediaRoom IPTV application. It turns out that MPF MRML applications don't support cookies; changing to use cookieless sessions in the web.config solved my issue
<sessionState cookieless="true" />
Here's a REALLY old article about it:
Cookieless ASP.NET
in my case it was because I was modifying session after redirecting from a gateway in an external application, so because I was using IP instead on localhost in that page url it was actually considered different website with different sessions.
In summary
pay more attention if you are debugging a hosted application on IIS instead of IIS express and mixing your machine http://Ip and http://localhost in various pages
In my case this was happening a lot in my development and test environments. After trying all of the above solutions without any success I found that I was able to fix this problem by deleting all session cookies. The web developer extension makes this very easy to do. I mostly use Firefox for testing and development, but this also happened while testing in Chrome. The fix also worked in Chrome.
I haven't had to do this yet in the production environment and have not received any reports of people not being able to log in. This also only seemed to happen after making the session cookies to be secure. It never happened in the past when they were not secure.
Update: this only started happening after we changed the session cookie to make it secure. I've determined that the exact issue was caused by there being two or more session cookies in the browser with the same path and domain. The one that was always the problem was the one that had an empty or null value. After deleting that particular cookie the issue was resolved. I've also added code in Global.asax.cs Sessin_Start method to check for this empty cookie and if so set it's expiration date to something in the past.
HttpCookieCollection cookies = Response.Cookies;
for (int i = 0; i < cookies.Count; i++)
{
HttpCookie cookie = cookies.Get(i);
if (cookie != null)
{
if ((cookie.Name == "ASP.NET_SessionId" || cookie.Name == "ASP.NET_SessionID") && String.IsNullOrEmpty(cookie.Value))
{
//Try resetting the expiration date of the session cookie to something in the past and/or deleting it.
//Reset the expiration time of the cookie to one hour, one minute and one second in the past
if (Response.Cookies[cookie.Name] != null)
Response.Cookies[cookie.Name].Expires = DateTime.Today.Subtract(new TimeSpan(1, 1, 1));
}
}
}
This was changing for me beginning with .NET 4.7.2 and it was due to the SameSite property on the session cookie. See here for more info: https://devblogs.microsoft.com/aspnet/upcoming-samesite-cookie-changes-in-asp-net-and-asp-net-core/
The default value changed to "Lax" and started breaking things. I changed it to "None" and things worked as expected.
Be sure that you do not have a session timeout that is very short, and also make sure that if you are using cookie based sessions that you are accepting the session.
The FireFox webDeveloperToolbar is helpful at times like this as you can see the cookies set for your application.
Session ID resetting may have many causes. However any mentioned above doesn't relate to my problem. So I'll describe it for future reference.
In my case a new session created on each request resulted in infinite redirect loop. The redirect action takes place in OnActionExecuting event.
Also I've been clearing all http headers (also in OnActionExecuting event using Response.ClearHeaders method) in order to prevent caching sites on client side. But that method clears all headers including informations about user's session, and consequently all data in Temp storage (which I was using later in program). So even setting new session in Session_Start event didn't help.
To resolve my problem I ensured not to remove the headers when a redirection occurs.
Hope it helps someone.
I ran into this issue a different way. The controllers that had this attribute [SessionState(SessionStateBehavior.ReadOnly)] were reading from a different session even though I had set a value in the original session upon app startup. I was adding the session value via the _layout.cshtml (maybe not the best idea?)
It was clearly the ReadOnly causing the issue because when I removed the attribute, the original session (and SessionId) would stay in tact. Using Claudio's/Microsoft's solution fixed it.
I'm on .NET Core 2.1 and I'm well aware that the question isn't about Core. Yet the internet is lacking and Google brought me here so hoping to save someone a few hours.
Startup.cs
services.AddCors(o => o.AddPolicy("AllowAll", builder =>
{
builder
.WithOrigins("http://localhost:3000") // important
.AllowCredentials() // important
.AllowAnyMethod()
.AllowAnyHeader(); // obviously just for testing
}));
client.js
const resp = await fetch("https://localhost:5001/api/user", {
method: 'POST',
credentials: 'include', // important
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
Controllers/LoginController.cs
namespace WebServer.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class UserController : ControllerBase
{
[HttpPost]
public IEnumerable<string> Post([FromBody]LoginForm lf)
{
string prevUsername = HttpContext.Session.GetString("username");
Console.WriteLine("Previous username: " + prevUsername);
HttpContext.Session.SetString("username", lf.username);
return new string[] { lf.username, lf.password };
}
}
}
Notice that the session writing and reading works, yet no cookies seem to be passed to the browser. At least I couldn't find a "Set-Cookie" header anywhere.

Cookies NULL On Some ASP.NET Pages (even though it IS there!)

I'm working on an ASP.NET application and I'm having difficulty in understanding why a cookie appears to be null.
On one page (results.aspx) I create a cookie, adding entries every time the user clicks a checkbox. When the user clicks a button, they're taken to another page (graph.aspx) where the contents of that cookie is read.
The problem is that the cookie doesn't seem to exist on graph.aspx. The following code returns null:
Request.Cookies["MyCookie"];
The weird thing is this is only an issue on our staging server. This app is deployed to a production server and it's fine. It also works perfectly locally.
I've put debug code on both pages:
StringBuilder sb = new StringBuilder();
foreach (string cookie in Request.Cookies.AllKeys)
{
sb.Append(cookie.ToString() + "<br />");
}
this.divDebugOutput.InnerHtml = sb.ToString();
On results.aspx (where there are no problems), I can see the cookies are:
MyCookie
__utma
__utmb
__utmz
_csoot
_csuid ASP.NET_SessionId
__utmc
On graph.aspx, you can see there is no 'MyCookie'
__utma
__utmb
__utmz
_csoot
_csuid ASP.NET_SessionId
__utmc
With that said, if I take a look with my FireCookie, I can see that the same cookie does in fact exist on BOTH pages! WTF?!?!?!?! (ok, rant over :-) )
Has anyone seen something like this before? Why would ASP.NET claim that a cookie is null on one page, and not null on another?
This was happening because I was running the app under a different virtual directory. When I ran it on the original one, it worked.
I would suggest loading the IIS debug diagnostics tools. It is entirely possible that on that particular server there is a resource problem or unhandled exception that is killing that particular cookie AFTER it is added to the response but before it is flushed to the user. This is basically caused by a series of exceptions that occur in rapid succession causing rapid fail protection to shut down the w3wp.exe process that your page is running under. When the process is spooled back up to feed the response, the cookie is gone and all that goes out is the rendered html.
You might also try turning off rapid fail protection or altering memory settings/recycling settings on the application pool.

ASP.NET and the Output Cache - how can see if it's working?

Problem: I've got an ASP.NET website and i don't believe that my code is getting OutputCached correctly. I'm using IIS7 performance counters to show me the hits or misses a second.
i've got a simple ASP.NET MVC website. I'm using the built in ASP.NET Output Cache magic.
Here's some sample code :-
[AcceptVerbs(HttpVerbs.Get)]
[ApiAuthorize] // <-- this checks the querystring for a "key=1234".
// Doesn't find it, then it throws a 401 NOT AUTH exception.
[OutputCache(CacheProfile = "HomeController_Foo")]
public ActionResult Foo(string name, byte? alpha, byte? beta)
{
}
so this means that each url query can be like the following :-
http://www.mydomain.com/Foo?name=hello+word&key=1234
http://www.mydomain.com/Foo?name=hello+word&alpha=1&key=1234
http://www.mydomain.com/Foo?name=hello+word&alpha=1&beta=2&key=1234
Now, notice how i've got the OutputCache referencing a config file? here it is...
<caching>
<outputCacheSettings>
<outputCacheProfiles>
<add name="HomeController_Foo" duration="3600" varyByParam="key;name;alpha;beta"/>
</outputCacheProfiles>
</outputCacheSettings>
</caching>
Nothing too hard ...
so here's the kicker! When I confirm that this is happening by using the IIS7 performance counters, it's saying that the output cache misses/sec are 100% of the requests i'm making a sec. Output cache hits are 0/sec.
I'm using a 3rd party web load stress testing program to bast my site with queries. Now, what's the source data? a list of names. The program keeps looping through all the names, then goes back to the start, rinse repeat. So it's BOUND to call the same query string at least once. IIS log files confirm this.
I'm not passing in any data for the alpha or beta.
this is my query string i'm hitting....
http://www.mydomain.com/Foo?name=hello+word&key=1234
... where i keep substituting the 'hello+world' with the names from the data source file and IIS logs confirm this.
So .. am i looking at the wrong performance counter? Are there any other tricks to see if it's getting outputcached? The code is very fast, so it's hard to tell if that is a cached result or not.
Probably way too late but to help others : If you had a cookie in your response header, that will prevent it from being cached. The outputcache (http) module has a lot of silent check to ensure the response is subject to being cached. Looking into it through reflection might give anyone candidate of failure to put in cache.
Use a tool like firebug and look at the response from the request. You'll be able to tell by the 200 or 304 whether the cache response was used (304) or if a successful response was sent (200).

Use the ASP.NET request user for Log4net log entries

My ASP.NET site is using Integrated Authentication with impersonation turned off. I have added a "%username" to my "conversionPattern" in the web.config to add the user name to each logging entry. However this will use the application pool identity's user name, and not the current visiting user's name.
Any ideas on how best to do this? Do I have to write a custom appender? I don't mind any minor performance penalties as this is a small intranet site. Thanks!
There's built in ASP.NET pattern converters in recent versions of log4net:
%aspnet-request{REMOTE_ADDR} and %aspnet-request{AUTH_USER}
https://stackoverflow.com/a/7788792/74585
You can also access the contents of
aspnet-cache
aspnet-context
aspnet-session
https://logging.apache.org/log4net/log4net-1.2.13/release/sdk/log4net.Layout.PatternLayout.html
An alternative (and easier) solution you may want to take a look at is to use the ThreadContext class (formerly implemented as the MDC and NDC classes). You could have something like this inside an HttpModule (before the request arrives at your page) or anywhere else before you log your first message:
ThreadContext.Properties["user"] = username;
And then include the following in your conversionPattern:
%property{user}

Resources