MVC jQuery ajax calls are not authenticated on the server - asp.net

A little background:
I have developed a web application in MVC3 that requires users to be logged in to access.
If the web page has been left for 5 minutes, a timer fires which makes a jQuery ajax call to the server, and returns a partial view which contains the logged in users email address, and a password textbox so that the user can re-enter their details before continuing to use the application.
I use Forms Authentication, with the cookie for it stored in the browser set to expire when the browser session closes (i.e. it does not have the Expires property set).
If I have the idle timer set to 10 seconds, or 1 minute, it works fine. If however I set it to 5 minutes, on the server the following is what I see:
HttpContext.Current.User.Identity.IsAuthenticated has value false
HttpContext.Current.User.Identity.Name has value "empty"
So I cannot get to the currently logged in users details.
Any ideas?

I have noticed that in my web.config, under the Authentication node, there is a timeout also set to 5 minutes which seemed to be affecting it. Hence why it worked fine for any requests below the 5 minutes mark. I changed this to 30 minutes and it appears at first glance to be working.

You can try keeping the settings of the user in web.config file, like isdebugmode,clientcode and fetch from there.
Dot net nuke is not a bad choice either.

Related

What will happen to the session after redirect?

I would ask a general question:
What will happen with the Session, Log-in cookie in the case situation:
The case is Redirect from a web application to another then the second application to the first one?
A => B => A
Will the be persist or a new one will be created? or something other?
It will persist, so long as the session hasn't timed out (default 30 minutes)
The cookie will stay in the browser, but is application specific. So in your example, if application A deposited a session cookie on the clients browser, application B would not be able to access it. If application B then redirects back to A before the session times out, you will still be able to access it in application A.
-Mikey
It would be persisted until the session times-out.
If the transition from B => A happens in the timeframe where the Cookie Data and the Session are valid you still will be logged in.
Beware Session Lifetime != Cookie life time
If a site proves additional information you may be logged out though. E.g. Refererer or something like this.

ASP.NET Forms Authentication failed for the request. Reason: The ticket supplied has expired

I am getting this error many times in the event log and users are logged out.
Event code: 4005
Event message: Forms authentication failed for the request. Reason: The ticket supplied has expired.
Event time: 3/10/2011 3:35:22 PM
Event time (UTC): 3/10/2011 8:35:22 PM
Event ID: fc2f70cc85014b0ca7dbb01471617b66
Event sequence: 3392
Event occurrence: 1
Event detail code: 50202
Thoughts:
I am not using web forms.
I do not think the app pool is recycling.
I compared the Process ID in several events and it is equal.
My machine key is not AutoGenerate.
AS Scott mentioned here http://weblogs.asp.net/scottgu/archive/2010/09/30/asp-net-security-fix-now-on-windows-update.aspx
After windows installed security update for .net framework, you will meet this problem.
just modify the configuration section in your web.config file and switch to a different cookie name.
Sounds like an error you would get when your forms authentication ticket has expired. What is the timeout period for your ticket? Is it set to sliding or absolute expiration?
I believe the default for the timeout is 20 minutes with sliding expiration so if a user gets authenticated and at some point doesn't hit your site for 20 minutes their ticket would be expired. If it is set to absolute expiration it will expire X number of minutes after it was issued where X is your timeout setting.
You can set the timeout and expiration policy (e.g. sliding, absolute) in your web/machine.config under /configuration/system.web/authentication/forms
Here is a good article from Microsoft http://www.iis.net/learn/troubleshoot/security-issues/troubleshooting-forms-authentication that covers various cases and scenarios.
I've had the same issue after using a web.config from another machine. The problem was related with an invalid MachineKey. To solve the problem, I modified the web.config to use the correct MachineKey of my server.
This MSDN blog post shows how to generate a MachineKey.
I was getting this same error, in our case it was caused by a load balancer. We hade to make sure that the persistance was set to Source IP. Otherwise the login form was opened by one server, and processed by the other, which would fail to set the authentication cookie correctly. Maybe this helps someone else

Setting cookie expiration with ASP classic to ASP.NET session sharing solution

I'm implementing the session sharing structure from this link for an ASP classic site to begin the gradual conversion process to ASP.NET. I'm trying to extend the cookie expiration time so that users do not get signed out of the site when the session expires. At the place where the cookie is created in SessionPage.cs I've added the line in the CreateNewSessionCookie() method:
cookie.Expires = DateTime.Now.AddDays(14);
Now this works fine, however, it only works if the user first visits an ASP.NET page, and then visits the ASP classic pages. It doesn't work if visiting an ASP classic page first (looking at the cookie through firefox confirms that different expiration values are given based on if I visit an ASP or ASP.NET page first.) I'm still a bit fuzzy on the mechanics behind this implementation as I don't have a complete understanding of session and cookie handling. However, I would have thought that the VB6 SessionMgr object is calling the SessionUtility DLL, and thus is using the same code to issue the cookie. I have re-registered the SessionUtility using gacutil, and re-exposed it using regasm. How else is the cookie being issued when a user accesses an ASP classic page? How can I change the expiration time?
This might be a total hack, but since you don't have any answers yet...
Iterate through the Request.Cookies collection in classic asp and find the session cookie (you should be able to figure out which one it is fairly easily). Then reissue that cookie Response.Cookies(sessioncookiename) = sessioncookievalue and set
Response.Cookies(sessioncookiename).Expires = Now() + 14

After a few window.open calls my ASP.NET session times out

I have an ASP.NET application that uses StateServer session mode with cookieless set to false. In a few places, there is a link that pops up a window to another application (which happens to reside on the same domain, but in a different virtual directory). The following steps give me grief...
Launch popup
Close popup
Launch popup to same app as before with a couple different parameters
Close popup
Next request = session timeout on the "parent" window.
Using cookieless sessions fixes the problem, so somehow my cookie is getting whiped out by the browser. Aside from using cookieless sessions, how can this be resolved? For what it's worth, I am developing/testing with IE8.
EDIT
It seems the problem only occurs when the popup resides on the same domain. If I popup a page elsewhere, there is no problem.
Is it possible the other app (on the same domain) is setting its own cookie, overwriting that of your primary app? Can you use fiddler (or similar tool) to see which cookies are being set by which apps?
Check all instances of your
Session.Clear();
Session.Abandon();
If you aren't using those at all, then its likely the case that your browser windows are set to NOT share sessions between. So the new instance gets a NEW session cookie (since its the same cookie name as the prior one, it could possibly kill the existing session cookie)- as in a play on:
http://geekswithblogs.net/ranganh/archive/2009/04/17/asp.net-session-state-shared-between-ie-tabs-and-ie8.aspx
Ideally track down in which page the Set-Cookie header is coming across. Look then at the request going INTO that response and see if your current ASP.NET_SESSIONID cookie is sent over. (fiddler is indeed the best tool for this)
Anyway - its a start to try.
edit Apparently it's not your cookie name, so...
Perhaps you should have an AJAX call on your master page that pings a service (or generic handler) on your web app to keep the session alive.
JavaScript
window.setInterval(function() {
$.get('ping.ashx?nocache=' + (new Date()).getTime(), function() {
return true;
})
}, 30000);
In the Generic Handler, make sure to add the IRequiresSessionState marker interface.
Perhaps your session cookie names are the same.
In your web.config (for one of the applications) change the session cookie name.
<sessionState
mode="StateServer"
timeout="20"
cookieName="DifferentASP.NET_SessionId"

Logoff button IIS6 ASP.NET Basic Authentication

I have a requirement for an explicit logout button for users in a ASP.NET web app. I am using IIS6 with Basic Authentication (SSL). I can redirect to another web page but the browser keeps the session alive. I have googled around and found a way to do it by enabling an active x control to communicate with IIS and kill the session. I am in a restricted environment that does not allow forms authentication and active x controls are not forbidden as well. Has anyone else had this requirement and how have you handled it?
Okay that is what I was afraid of. I have seen similar answers on the net and I was hoping someone would have a way of doing it. Thanks for your time though. I guess I can use javascript to prevent the back button like the history.back()
I was struggling with this myself for a few days.
Using the IE specific 'document.execCommand('ClearAuthenticationCache');' is not for everyone a good option:
1) it flushes all credentials, meaning that the user will for example also get logged out from his gmail or any other website where he's currently authenticated
2) it's IE only ;)
I tried using Session.Abandon() and then redirecting to my Default.aspx. This alone is not sufficient.
You need to explicitly tell the browser that the request which was made is not authorized. You can do this by using something like:
response.StatusCode = 401;
response.Status = "401 Unauthorized";
response.AddHeader("WWW-Authenticate", "BASIC Realm=my application name");
resp.End();
This will result in the following: the user clicks the logout button ==> he will get the basic login window. HOWEVER: if he presses escape (the login dialog disappears) and hits refresh, the browser automagically sends the credentials again, causing the user to get logged in, although he might think he's logged out.
The trick to solve this is to always spit out a unique 'realm'. Then the browser does NOT resend the credentials in the case described above. I chose to spit out the current date and time.
response.StatusCode = 401;
response.Status = "401 Unauthorized";
string realm = "my application name";
response.AddHeader("WWW-Authenticate", string.Format(#"BASIC Realm={0} ({1})", realm, DateTimeUtils.ConvertToUIDateTime(DateTime.Now)));
resp.End();
Another thing that you need to do is tell the browser not to cache the page:
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.MinValue);
Response.Cache.SetNoStore();
With all these things in place it works (for me) in IE, but until now I still wasn't able to prevent firefox from logging in the user when the user first presses escape (hides the basic login dialog) and then refresh (F5) or the browsers back button.
The Session.Abandon method destroys all the objects stored in a Session object and releases their resources. If you do not call the Abandon method explicitly, the server destroys these objects when the session times out.
Have you tried calling Session.Abandon in response to the button click?
Edit:
It would seem this is a classic back button issue.
There is very little you can do about the back button. Imagine the user has just opened the current page in a new window then clicked the logOut button, that page appears to log out but it will not immediately affect the content of the other window.
Only when they attempt to navigate somewhere in that window will it become apparent that their session is gone.
Many browsers implement the back button in a similar (although not identical) way. Going back to the previous page is not necessarily a navigation for a HTML/HTTP point of view.
This is a solution for this problem that works in IE6 and higher.
<asp:LinkButton ID="LinkButton1" runat="server" OnClientClick="logout();">LinkButton</asp:LinkButton>
<script>
function logout()
{
document.execCommand("ClearAuthenticationCache",false);
}
</script>
Found this from
http://msdn.microsoft.com/en-us/library/bb250510%28VS.85%29.aspx
Web Team in Short
Your Credentials, Please
Q: Jerry B. writes, "After the user has validated and processed his request, I now want to invalidate him. Assuming this machine is in an open environment where anyone could walk up and us it, I want to throw a new challenge each time a user accesses a particular module on the Web."
A: This is a frequently requested feature of the Internet Explorer team and the good people over there have given us a way to do it in Internet Explorer 6.0 SP1. All you need to do is call the execCommand method on the document, passing in ClearAuthenticationCache as the command parameter, like this:
document.execCommand("ClearAuthenticationCache");
This command flushes all credentials in the cache, such that if the user requests a resource that needs authentication, the prompt for authentication occurs again.
I put this on my logout link button and it works in IE6 sp1 and higher:
OnClientClick="document.execCommand('ClearAuthenticationCache');"

Resources