ASP.NET MVC3 creating new sessions on ajax requests - asp.net

Well, I finally had to create an account here. Been using this for years and have often found my answer here, but not this time.
Well, I actually have found a lot of people with similar problems, but none of their solutions have helped me.
I have started on a new MVC3 project, so it's quite simple so far. I've made a handful before, so I kinda know what I'm doing (but not quite, obviously, why else be here ;-)
My problem is apparently a fairly common one: A request starts a new Session, even though the user already has one.
The most frustrating part of this is, it works perfectly on my hosted service, but is broken on localhost.
I have done a number of things to solve this:
There is no underscore in my computer's name.
The Session contains custom data (the error only occurs after user has logged in).
I have added the following to web.config (hmpf, guess you'll have to assume the gt / lt chars):
httpProtocol
customHeaders
clear /
add name="Access-Control-Allow-Origin" value="*" /
/customHeaders
/httpProtocol
and this too:
modules runAllManagedModulesForAllRequests="false"/
With InProc sessionstate, I have tried with 'cookieless' both true and false.
My hosts file contains nothing about localhost.
hm. Looking at this list I'm sure I've left some out. Some on purpose too, as they were hopeless (yes, even more than the above), and born from desperation.
As mentioned this is particularly unnerving as it works on my host - could there be some configuration settings I need to tweak on the dev server (VS2010)?
I've been working from the premise that the issue is due to cross-domain security (it thinks I'm coming from another domain).
The fail happens on this request:
url: 'http://localhost:50396/moody/changeBuilding/' + elem.selectedIndex,
It's part of the options array I use with the jQuery.ajax function.
I change the domain when uploading to the host, but only the part localhost:port, everything else in the application is identical.
I've been banging my head against this for 2 days now, and will miss my exam :-(
I'm determined to bury this 6 feet under, though.
I would be very grateful for any and all suggestions!

I change the domain when uploading to the host, but only the part localhost:port, everything else in the application is identical.
Reading the above, I image the session cookie isn't being sent because you're changing domains.
Let's sit back and think about how sessions work. Basically ASP.NET contains a collection of sessions and their data. When each request comes in, ASP.NET must map that request to an existing session OR create a new session for them.
So how does ASP.NET know what session belonged to each incoming request? Or know that it needs to create a new request? The only way to know this is if the request contained some information, a 'key', which told ASP.NET what session to give the request... or in the absence of this 'key', create a new session.
How does the request send this 'key'? Through cookies.
So therefore, if you change the domain, the cookies isn't going to be sent... so therefore, ASP.NET will create a new session for the request.

Have you tried using something like fiddler to make sure that the session cookie is being sent in the AJAX request. It should be sent if the domain is the same but it's work checking.
Edit: This SO post on changing ports is worth reading too.
Edit: Given the new information in Charlino's comments (and the sterling detective work carried out therein) if the problem is only on your local dev machine then the easiest way to work around your localhost/127.0.0.1 issue is by manually changing the browser url from 127.0.0.1:50396 to localhost:50396, logging in again to get the new cookie, then you are good to go.

Related

OpenLaszlo 4.9 DHTML login servlet forwards but never loads page

I am having some problems at the moment using a LoginServlet running OL 4.9, on Tomcat 7.
I have Tomcat configured to allow crossContext to be true, and that allows me to work with other app contexts on the same server. Specifically a Login Servlet. My only other app is the OpenLaszlo presentation server LPS(lps-4.9.0).
I am using a Tomcat Request Filter that snoops the incoming addresses and looks for a particular cookie of authentication, which then makes its way to the LoginServlet that does a forwarding to the OpenLaszlo page. This was done to KEEP the cookie alive when the Request Filter was awakened at the loading of the OpenLaszlo page.
All of that is working now.
There are no errors or warnings in the lps.log file or the localhost.<date>.log either, however the page loading goes on forever, and never completes.
Could it be something that I am passing along in the forwarded URL? I am using at least 2 parameters to cause lzr to be set to "dhtml" and then lzt to be set to "html."
I can't even get a simple <canvas> page with a simple button to load. Has anyone seen this, and been able to fix the problem?
Since I first wrote my description I wrote another plea for help to some friends and ex coworkers, and this will help update the details of what I have discovered thus far.
Here’s the scenario: I am using Tomcat 7, and have installed the WAR file for OpenLaszlo 4.9.
Alongside of this I created a LoginServlet hierarchy and code and web.xml file just under
“webapps”; the same level that lps-4.9.0 is installed.
The sequence of events is the following:
1. A login page comes up that takes the username and password, and sends that
off to /LoginServlet to process. Note: I have also written and registered a Request Filter
for Tomcat that halts traversal beyone /lps-4.9.0 and checks for proper authentication
as I retrieve the cookies from requests trying to access those levels.
2. In the LoginServlet, I am creating a MACH COOKIE that I’ll send along with the response,
so that the Filter will allow me past the /lps-4.9.0 level. To do this I had to do a FORWARD
operation to preserve the cookie. a REDIRECT would just drop them. Since you can’t
give a relative path higher than the Servlet’s root, I had to turn on Tomcat’s “crossContext”
feature that allows me to do that in the same domain. And I have both contexts registered
in Tomcat’s conf directory in server.xml, I believe. Anyhow it works. I can grab the
/lps-4.9.0 context, get a Request Dispatcher, and then use that dispatcher to FORWARD
the request/response pair to my OpenLaszlo file(the LZX file).
So it seems to get as far as LOADING the OpenLaszlo page, but when I perused the console
messages in Chrome’s Developer Tools debugger, it showed that it was actually trying
to use the context of the original request(i.e. /LoginServlet); and of course that doesn’t
exist. I guess when I passed along the original request/response pair, the request had
the FIRST context used, and then tried to derive the relative path to the file off of that.
QUESTION: Can I just copy the stuff from the original request, but change the context,
and forward THAT?  Or architecturally should I try something else?
Thanks,
C
And the answer is..... You CAN'T DO IT... Period.
BTW. The Openlaszlo website server is DOWN, DEAD, KAPUT, NIX, GONE, NO MORE...
This will be the final project that I personally implement with the tool
with no support.
It's very sad to see something that had the right idea about development cycle times,
and keeping the client side GUI construction simple, fast, and easy could be something
that dies because of lack of interest? Say wha? Can't be because FLASH was in jeopardy.
I'm pretty sure that we, as programmers, aren't so paranoid about losing our jobs
that we think we must spend lots of hours CODING an interface to keep it secret.
I'm certainly not paranoid about it. I know there is NET BEANS for swing type
GUIS, and I've heard that GWT has adopted something similar now, and so I'll
keep looking for that perfect invention and deal with what is left over.
Critical Path must have been purchased by someone else too, and so the
site sponsor has no motivation to keep it alive, while it dies a slow death.

1% of Users get new Session ID on each page request

We just upgraded to IIS7 and have had intermittent issues with SESSION variables. In a nutshell a very low percentage of users are getting new SESSION IDs with each page request. Clearing cookies has solved this problem for just about every use I've come across.
My question is... Is there a way to programmatically do this? It's been a lower percentage of calls of people unable to login/can't get a certain application to work, so it's not a HUGE deal, but we are having to walk people through the process of clearing cookies all day. I haven't read of, nor seen a way to force users to clear cookies.
Most other questions on here are uses having this issue everywhere, as if there is a programmatic error. Our applications work fine, it's just a small percentage of users who used our applications on our old server can't get new session cookies from the new server.
We were running IIS6/CF9 and we upgraded to IIS7/CF10. This problem is cross browser. We have seen it turn up in IE, FF, and Chrome.
--EDIT--
If a user clears cookies and goes to domian.com and then to sub.domain.com, the domain.com cookie takes precedent and the browser I guess never returns the sub.domain.com cookie it gets from the sub.domain.com server. Turning on J2EE cookies on sub.domain.com fixes the issue, I guess, but the clients still run around with a cookie from domain.com. domain cookies is whatever is set by default... i.e. we don't set it to anything in app.cfc. I have no idea how it is set on domain.com.
In Application.cfc do you have domain cookies set to true?
Sounds like it could be related to the session fixation Hotfix Adobe introduced in February last year. Was your CF9 server fully patched?
In short, CF now issues new CFID/TOKEN values on every session and won't use existing cookie values (to prevent session hijacking). Make sure your app is writing these new values to cookies and not allowing existing cookie values to be used.
Here's a detailed explanation As pointed out in the comments on that post, using J2EE sessions is indeed one way of solving the problem.

asp.net, stateserver, NLB, session lost

1st post on stackoverflow, hope to have great feedback :)
I'm currently trying to load balance our web site. We have set up a 2 cluster NLB on windows server 2003 with IIS 6.
While testing the setup, I found that sometimes, our session is lost. A day and a half later, here's the result:
Yes, our machine.config both have the same encryption/decryption key.
Yes, the id in iis metabase.xml are the same for both machine. Actually, the entire file are the same, except for "AdminACL".
Both web application are set with "StateServer" and both pointing at the same machine.
From that point, searching on google gives less information and possible solutions.
From what I know, there's no particular pattern that cause this problem. It just happen once in a while.
While trying to find the problem, I've seen that a request sent the asp session id cookie to the server, but the server didn't map it to the user session.
So the request number x was sent from the client, with the cookie, session was mapped, and everything went smoothly.
The request number x+1 was sent from the client, with the cookie, but session was not found.
Both request were made on the same machine in the NLB.
Here's a snippet of the asp trace.axd:
1st request:
Request Details
Session Id: j2ffvy45updpc52uhw1mbg55 Request Type: GET
Time of Request: 11/26/2008 2:58:06 PM Status Code: 200
Request Encoding: Unicode (UTF-8) Response Encoding: Unicode (UTF-8)
Request Cookies Collection
Name Value Size
ASP.NET_SessionId j2ffvy45updpc52uhw1mbg55 42
AID 22 9
Response Cookies Collection
Name Value Size
Headers Collection
Name Value
Cookie ASP.NET_SessionId=j2ffvy45updpc52uhw1mbg55; AID=22
2nd Request:
Request Details
Session Id: Request Type: POST
Time of Request: 11/26/2008 2:58:08 PM Status Code:
Request Encoding: Unicode (UTF-8) Response Encoding:
Request Cookies Collection
Name Value Size
Response Cookies Collection
Name Value Size
Headers Collection
Name Value
Cookie ASP.NET_SessionId=j2ffvy45updpc52uhw1mbg55; AID=22
As you can see in the 2nd request, the cookie is sent from the client, but asp seems to never add the cookies in it's "Request Cookies Collection". I think that's why it doesn't find the session.
So why the cookie is not mapped to the session? Is that the problem? Is the problem elsewhere?
Feel free to ask any clarifications.
Thank you all for your feedback.
JF
I finally found the answer to my problem. It's origin are within the application code (like 99% of a programmer's 3rd party tools 'bugs'). I decided to post it anyway in case someone is in a similar scenario.
This code was part of WebServiceRequester class. The web service requester class was instanciated when session was created and it is saved in session. During creation, we initalizate the member 'm_webServiceURL', and this member is saved in session after. At which value was this member initialize was depending on a setting on the local machine.
The important part is the following:
WebServiceRequester class contains a WebService objects.
WebService objects can't be saved in session, they are not serializable in asp. The property had the [NonSerialized] attribute on it. So everytime we accessed the 'WebService' property of the object for the first during a page life cycle, we had to create a new one, and assigning ot it the url 'm_webServiceURL' which was saved in session.
So you see, new webservice object, on possibly a different machine, meaning a different setting on each machine.
so here's what happened:
box 29 was set to access Web Service at localhost
box 30 was set to access Web Service as 192.168.253.29.
Technically, they are both set on the same machine. But here's a scenario:
login on box 29. m_webServiceURL is set to localhost in session.
[some request on box 29 here]
NLB balancing bring us on box 30.
box 30 loads it's session, create a new webservice obect with localhost as the web service address.
box 30 made the request to the wrong web service leading to a Session Expired exception.
One of the problem during the debug, was that the local communication were not recorded with the network monitor.
What lead me on the trace, was that we never had an exception logged on the box 29 log trace, as it should have.
Thanks for you suggestions everyone, it was really appreciated.
Have a good day.
JF
Not strictly an answer to your question, but have you tried it using a sql server based session store? (Search on MSDN for the permanent script rather than the temp script that's provided with asp.net)
I've heard "bad things" about the executable session service, and consequently have not used it. Never had any problems web farming with the sql server based solution though.
Sorry it's not strictly an answer to your problem, but it should either (a) fix it, or (b) narrow it down significantly.
Well, if you're using visual studio, you could at least test it with the MSDE (the cut down version of SQL Server that comes with Visual Studio)...
It might help rule out state server problems...
Using the database approach has its own issues. I think you should be able to use your preferred approach.
Perhaps this session troubleshooting article would help?
Or "Troubleshooting Session Related Issues in ASP.NET"
Or "Troubleshooting Expired ASP.NET Session State and Your Options"
I'll be lame and re-iterate the proposal of MS SQL Server. Install SQL Server Express which is completeley free including for commercial use and it has only these 3 drawbacks which shouldn't be a problem for you in this stage :
Max 4GB size database
Max 1 CPU Core used
Max 1GB RAM used
A few points to take into consideration:
What's the load on your website? State Server has the tendency to crash when facing a large number of concurrent hits. We're only using it in scenarios where we have a really small number of users (in the 10's, mostly backend systems). Whenever we tried using it in production for sites serving 1000's of users daily, it would crash leading to loss of session data.
On one of the production environments we manage, we're using MSSQL 2005 Express to manage the sessions, the site has 10K+ users a day and 200K+ pages a day. This is a recommended approach in case session is a must and tightly coupled into your application.
If you're about to user MSSQL Express as your state DB, remember that it doesn't come with SQL Server Agent meaning there's no tasks scheduler running in the background and cleaning your expired sessions. I'd recommend finding a scheduler and running the clean expired sessions stored procedure periodically.
Good luck
Instead of messing around with SQL, send your tests directly into one of your IIS nodes to see if you still get the same issue. I'm sure if your only doing a small number of tests StateServer won't be the issue.
Try setting the domain name of the asp.net_sessionid through code to ".yourdomain.com".
By default the ASP.net_SessionID cookie domain name is set to the full application path. So, this may be one of the reason why the cookie is not travelling.
E.g.
Request.Cookies["ASP.NET_SessionId"].Domain = ".yourdomain.com".
Remember the first "." is important in the domain name.
You could do this in the HttpModule in the AcquireRequestState event.

What is the best workaround for the ASP.NET forms authentication timeout when using wildcard mapping?

My team is working on a crappy old website and most of the pages are still ASP classic. However, we've recently migrated to forms authentication using ASP.NET and wildcard mapping. Everything works surprisingly well except for one thing: logged in users are timing out too quickly. After looking in the logs it appears people are timing out exactly after 20 minutes (which is the specified timeout due to inactivity).
So, our hypothesis is that the ASP classic pages are not tripping whatever mechanism in the forms authentication framework that resets the inactivity timer. I've googled around and even read the wildcard mapping post by the Great Gu but still can't find anyone else who is having this problem. So, 1) Have you ever seen this problem? and 2) What's the best workaround? (other than manually placing a hidden frame in every janky ASP page that loads a dumb .NET page in the background)
Update: slidingExpiration is set to true
Also: We can't use perpetual sessions because we need the application to time out after 20 minutes of inactivity. Also, this terrible site was written so that the interface is usually stored in the page. There's no simple piece of interface code I could slip the JavaScript into. We tried to put some js into an include file that was called by about 80% of our pages but it's caused some esoteric problems with file download buffers so we may have to try a different tack. Thanks.
Create a perpetual session.
Essentially you end up emitting some JavaScript and an image tag in your master page or navigation users controls (whatever you're using for consistent navigation). This JavaScript on some interval changes the source of the image tag to an http handler endpoint (some .aspx, .ashx) which returns a 1x1 pix clear gif as a response for the image. The constant request ensures that idle pages will keep the session alive.
As long as a browser window is open to your page your ASP.NET session will never time out.
Often the JavaScript will tack on a random number to the request so that the browser doesn't cache the request.
A decent walkthrough is available here.
I am assuming that you have manually created the cookie, in which case your timeout value in code is probably overriding your timeout value in the configuration.
First, if possible (which it probably isn't) don't create the cookie manually, it will save you from not only this headache but dozens of others.
If you must manually create the cookie, make sure that the timeout you are using is actually reading the timeout value that you have set in the configuration file and that sliding expiration is set to true (which you have said it was).
That said, we still have ocassional strange timeout problems when the cookies are manually created. Where I work we implemented a solution which allowed the cookies to be created automatically and timeouts were no longer a problem; however, it did create other issues and we were forced to switch back.

How can I share a session across multiple subdomains in ASP.NET?

I have an application where, in the course of using the application, a user might click from
virginia.usa.com
to
newyork.usa.com
Since I'd rather not create a new session each time a user crosses from one subdomain to another, what's a good way to share session info across multiple subdomains?
You tagged this with ASP.NET and IIS, so I will assume that is your environment. Make sure you have this in your web.config:
<httpCookies domain=".usa.com"/>
If your 2 subdomains map to the same application, then you are done. However, if they are different applications you will need to do some additional work, like using a SQL Server based Session storage (and hacking the stored procedures to make sure all applications share the same session data) or with an HttpModule to intercept the application name, since even with shared cookies and the same machine key, 2 applications will still use 2 different stores for their session data.
Track your own sessions and use a cookie with an appropriate domain setting, ie. .usa.com.
Alternatively, if you're using PHP, I believe there's a setting to change the default domain setting of the session cookie it uses, that may be useful too.
The settings you're looking for are:
session.use_cookies = 1
session.use_only_cookies = 1
session.cookie_domain = .usa.com
I recently went thru this and learned the hard way. Localhost is actually considered a TLD. Cookie domains require at least a second level domain - test.com. If you want cookies to work for a domain and all it's sub-domains, prefix with a '.' - .test.com.
When running/debugging locally, setting a domain of localhost will fail, and it will fail even if the domain is set properly because visual studio uses localhost by default.
This default localhost can be changed in the project properties so that the project will actually run at cookie domain test.com. Essentially, if the address in the browser matches , you can get it to work.
My issue is documented here: Setting ServiceStack Cookie Domain in Web.Config Causes Session Id to Change on Every Request
Hope this helps.
If you're using PHP, one hack would be to make a little include script (or two) to do the following:
1 Serialize your $_SESSION array
2 Pass that string as a hidden input, making all your links to those buttons in separate forms using POST.
3 Also include a boolean hidden input to let your script know whether it needs to use the current session or unserialize $_POST['session']
4 Deploy this across your site, calling things where appropriate
I wouldn't do this if there's actually a sanctioned way to transfer a session. I hope you've at least considered using cookies.
Matt's answer is definitely the way to go if you have multiple subdomains pointing at the same IIS app (which is exactly the situation I have right now, using wildcard DNS and then doing subdomain 'sniffing' on the receiving end).
However, I wanted to add something that I experienced in case anyone is finding that this is not working for them. Setting the httpCookies line alone didn't do it for me, I had to add a machineKey entry into my web.config file:
machineKey decryptionKey="12...D1" validationKey="D7..8B"
Particularly odd since I am not in a web farm setup (unless AWS/EC2 is effectively acting as such).. As soon as I did this, it worked like a champ.

Resources