Testing session timeout in C# - c#

I have my session timeout set to 1 in web.config.
I wanted to check whether session start and end occurs as expected, so I had this in my global.asax.cs-
//In Session_Start
Response.Write("<script>alert('session started');</script>");
//In Session_End
Response.Write("<script>alert('session ended');</script>");
I get the alert when session starts but not when it ends. When I put breakpoints, I see that the line is executed in Session_End but there is no alert on the screen.
This is my first time working with sessions and even though I was able to test the functions another way, I am curious why it did not show the alert.
Thanks in advance.

I know you are looking to write to the response and not redirect but have a look at this: Redirecting to another page on Session_end event
another-page-on-session-end-event
Session_End is called when the session ends - normally 20 minutes after the last request (for example if browser is inactive or closed).
Since there is no request there is also no response.
This would strongly suggest that you cannot write to the response... because there isn't one.

Related

Why IE Keeps sessions alive?

Hy all!
I'm developing a MVC 4.0 web application with C# and came accros the following error.
In major browsers (Chrome, Mozilla Safari, etc...) when i click logout in my web application it does the correct, logout the current user.
When i do the same operation on IE, dosen't work, i login with the new user, and IE keeps the last user until i press ctrl+F5.
The only thing i'm using for authentication is Sessions, nothing more.
Someone came acrros this issue? i've tried clear cache, clear sessions with abadon, clear, removeall and nothing seems to work when i'm on IE.
If you guys need some more info to help me with that, i'll answer as soon as possible!!
I've found the following works:
Session.Clear()
Session.Abandon()
Session.RemoveAll()
If Request.Cookies("ASP.NET_SessionId") IsNot Nothing Then
Response.Cookies("ASP.NET_SessionId").Value = ""
Response.Cookies("ASP.NET_SessionId").Expires = DateTime.Now.AddMonths(-20)
End If
Usually, browsers implement it so that ctrl+f5 means "make an http request for the current url, without the browser cache). So, no matter what you do after the fact in your server-side code, because IE is by default reloading the current page from its local memory without even hitting your server, you will not appear logged out. Then, when it does eventually go back to your server, it's still sending the same cookie because the page that would have logged you out is never actually hit.
One way to test if this is happening, is to set a breakpoint in your logout code. Refresh the page without holding ctrl in IE, and see if the breakpoint is even hit. If it's not, then you know client-side caching is the cause.
Workarounds:
This code on the server will send the page with metadata indicating the browser is not allowed, under any circumstances, to cache the page on their side:
response.Cache.SetAllowResponseInBrowserHistory(false);
response.Cache.SetCacheability(HttpCacheability.NoCache);
response.Cache.SetNoStore();
response.Cache.SetExpires(DateTime.Now);
response.Cache.SetValidUntilExpires(true);
-- or --
When you go to your logout page with a link like this: /logout or /home?logout=1 add an extra paramter like this: /logout?cacheBust=123yt74y5t, making the last part random. This works because most browser caches will cache based on url, so if you randomly mess up an unimportant part of the url, you can get around it. One advantage to this method is that you actually want the browser to cache some pages, but not others, and this is a more client-side way of determining if you want a fresh copy from the server or not.

Redirecting to another page from Session_end in global.asax

I need to redirect the user to the login page on session timeout. The issues with Session_End method in the global.asax are:It does not support Response.Redirect or Server.TransferAny attempt to use HttpContext.Current.Response results in 'Object Reference not set to an instance of an object' error The second error is understandable since on session time out, the current session would be terminated and set to null.
What I want to know is whether is it possible to redirect the user directly (and specifically) from session_end to another page. There are methods which work (not using the session_end method), but all of them require a request to the server(such as a refresh,which I don't want). Can i do this without using javascript?(more important, should I?)
Thanks in advance!
Isn't Session_End raised directly on server, without any interaction from user?
What happens, when I go to your page (and start a session), close browser window and never return? Then it's understandable, that HttpContext.Current.Response is null.

ASP.NET SessionState TimeOut not working

I want my web page to close when SessionState timeout occures. This is my code in my web config:
<system.web>
<sessionState timeout="1" mode="InProc"/>
</system.web>
I set to 1 minute for testing purposes. The following is my Global.asax code:
protected void Session_End(object sender, EventArgs e)
{
Response.Redirect("~/LogOut.aspx");
}
I put a label on one of the pages in order to check the session timeout, this is the code in the Page_Load event:
lblSession.Text = "SESSION TIME: " + Session.Timeout.ToString();
When I enter the site and come to this page the label shows SESSION TIME: 1, but after 1 minute I don't get redirected to the LogOut page and the present page is still fully active and working, apparently meaning that the session has not been terminated.
I am working in Visual Studio 2008 thru the development server so suggestions I've seen relating to IIS settings don't seem to be relevant at this stage.
Please help!
HTTP is a request / response protocol. There is no persistent connection between the browser and the server. The code in Session_End thus effectively does nothing — it can't tell the browser to do anything.
You would need to make a (client-side) JavaScript timer and actively load the logout page right before the session timeout elapses.
Session_End in my experience gets called on the first postback (could be implemented via a client-side Timer) after the timeout occurred - whenever that might be... if the user just closes the browser this event may never be called (except for the case you made a specific JS handler unload to do the postback in that situation).
For some information see:
http://justgeeks.blogspot.com/2008/07/aspnet-session-timeouts.html
http://www.highoncoding.com/ArticleDetails.aspx?articleID=108
http://forums.asp.net/t/1271309.aspx/2/10
http://www.codeproject.com/KB/aspnet/PageTracking.aspx
http://p2p.wrox.com/asp-pro-code-clinic/1648-session_onend-not-firing.html
http://aspalliance.com/1182_Troubleshooting_Session_Related_Issues_in_ASPNET.all
This doesn't seem to be the correct way of testing your session timeout. Try putting something in the session variables. Don't touch the page for another couple of minutes, and try reading it back from Session. If your session is alive, you should be able to see the variables, else... you won't.
Learn more about session and troubleshooting session... http://aspalliance.com/1182_Troubleshooting_Session_Related_Issues_in_ASPNET

Call a method on browser closing

I am facing an issue in my application when a user directly clicked on browser close [X] button. Browser can be IE, Chrome, Mozilla, Firefox and many more.
What I want to do:
1. as soon as user hits [X] button of browser, need to set their status as logged off in database for which we have a method in Login.aspx file which is within the master page.
2. We do not have any Logoff feature in the application
I will be thankful if anyone suggests a solution to call the method which sets the user status as logged off from master page.
Thanks in advance.
This is not possible due to the nature of http connections and the web in general. Simply have a timeout (eg. 10 minutes) after which a user gets logged out automatically.
Javascript has an onunload function, so you could do:
<body onUnload="doFunction()">
However this, and other methods are going to be unreliable (I'm not sure in which specific instances it is fired) as it would be a security concern allowing websites to have access to perform many functions on browser onunload.
The best solution would be to have cookies/sessions automatically time out, and also to educate users to logout if the system is sensitive.
If you are using jQuery you could work with
$(window).unload( function () {
$.ajax({ **your params** });
} );
But I have to agree with Tom Gullen here - your sessions should timeout eventually.

Possible to get return url back from javascript/jquery?

I have a problem that when a user times out on my site they are still logged in. So they can still do an ajax request. If they do an ajax request on my site my asp.net mvc authorization tag will stop this.
The authorization normally then redirects the user back to the signin page if they fail authorization.
Now since this is an ajax request what seems to be happening is it send the entire page back rendered as html. So the user never gets redirect since I just got the entire page send to me as html.
However firebug says this in the console:
http://localhost:3668/Account/signIn?ReturnUrl="return" ( this is not in the actual url bar in the web browser so I can't go up there and get it. I only can seem to see it through firebug.)
So I am not sure but maybe if I could somehow grab this url from inside my errorCallback area that would be great.
Since from my testing no error code is sent back(200 OK is sent). Instead I just get parsing error(hence why errorCallback is called) but I can't assume that every time I get parsing error it means the user timed out.
I need something better. The only other option is too look at the response and look for key works and see if it is the signin page what I don't think is that great of away to do it.
You probably want to do one of two things:
Write your server code such that ajax requests return an ajax error when a session is expired. That way the javascript will expect a return code that indicates a session timeout, and you can tell the user the session expired.
If an elegant solution isn't forthcoming because of how your framework handles this stuff, just put a chunk of HTML comment in your login page like Uth7mee3 or something; then check for the existence of that string in your ajax code.
Alternative, you can also set a timer on the web page that figures out when the session is about to time out and warn the user with a little message that lets them renew their session. Once it times out, blank out the page and give them a link to login again.
How about having a script in the Loginpage
if(document.location.href != "/Account/Login")
{
document.location.href = "/Account/Login"
}
This would work if you try to render partials in an ajax request.
(Not if you expect json)
What is the status code of the response in this situation? I think you should be able to check for a 302 here. If not, the Location header would be the next best way to check for the sign-in page.
This isn't an answer to your specific question, but the way I deal with this is to have a some client-side code that understands about the session length and prompts the user to renew a session just prior to it being ready to expire if they haven't moved off the page. If the user doesn't respond to the prompt in time, it invokes the logout action of the site -- taking the user to the login page.
You can find more information on the exact implementation, including some code, on my blog: http://farm-fresh-code.blogspot.com.

Categories