Close the browser when session expires? asp.net - asp.net

I have an asp.net web page that has a 60 second idle-time window before the session will expire. Is there a way (either through asp, or c# code behind) to close the browser - or preferably just the tab - in the Session_End event?
I've seen a lot of posts on SO that want to do the opposite (end the session on browser close), but not what I need.

You can't close the browser but you can redirect to a "Session Expired" page by doing this:
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
this.PageHead.Controls.Add(new LiteralControl(
string.Format("<meta http-equiv='refresh' content='{0};url={1}'>",
Session.Timeout * 60, "SessionExpired.aspx")));
}

You can look at this example - Alert Session Time out in ASP.NET
It basically warn the user before timeout (For example, Bank Of America site). Once it reaches the time limit, redirect user to a logout page.
FYI: User will get mad if you redirect or close a page without warning.

Related

check session is about to end then show alert to user

can we check that if user session set into IIS, is about to expire with in some second
and if it is then can we show any alert or notification to user
You can set session timeout to some value say 30 minutes. Use javascript code to detect user inactivity or idle time.
If the user is inactive for say 20 minutes, you can show him the popup or link to the user saying do you want to continue your session. If the user click the link his session will continue, otherwise he will be redirected to logout page.
Detecting Idle Time
This article has very clear and good example: Alert-Session-Time-out-in-ASP-Net
there are examples of how to alert the user, redirect to home page or extend session
What you cannot do is know "if session is about to expire with in some second", what you can do however is redirect the user to some page when the session has ended. Add this to your Global.asax
protected void Session_End(object sender, EventArgs e)
{
Response.Redirect("sessionend.aspx");//Youe page which greets the user the session is over
}

ASP.NET: what's wrong with this online users counter?

I'm trying to count the amount of online users.
This is the code:
protected void Application_Start()
{
...
Application["OnlineUsers"] = 0;
}
private void Session_Start(object sender, EventArgs e)
{
Application.Lock();
Session["O"] = "OO"; // Need to have something in the session
Application["OnlineUsers"] = (int)Application["OnlineUsers"] + 1;
Application.UnLock();
}
private void Session_End(object sender, EventArgs e)
{
Application.Lock();
Application["OnlineUsers"] = (int)Application["OnlineUsers"] - 1;
Application.UnLock();
}
There are <b>#Context.ApplicationInstance.Application["OnlineUsers"].ToString()</b> users online
It kind of works, but I always have the value that is greater than the actual amount of users online.
And even worse: in Opera refreshing the page N times increases the amount of online users by N!
It is important to note here that the ASP.NET is trying to be extremely efficient storing sessions for users. If ASP.NET doesn’t have a reason to remember who you are, it won’t.
When we request a page first time, a session object will be created and its session identifier will be sent to web-browser so browser can store session identifier in cookie (for identiity of request). If that page is again submitted/postedback then the same session identifier from the cooike will be available to the app-server and it assume that this is an old-request. But in your case (you are refereshing a page), it means web-browser issue a fresh request (and of-course the request type will be GET) without sending cookies. So, it is better to redirect the user to a specific page on first request.
The Session_End event handle will be called when Session get timeout (default value is 20 minutes) even after that client (browser) is closed (or ends the session).
I know its not quite what you are asking but you can query the PerformanceCounter on IIS for this info
(Razor Example)
#using System.Diagnostics
#{
var perf = new PerformanceCounter("ASP.NET", "State Server Sessions Active");
}
<h2>About</h2>
<p>
#perf.NextValue()
</p>
I didn't check but your access to this might need a windows/service account in your app pool.
You can also Increment and Decrement you own Performance counters and make them available to system admins via the tools they use to monitor Websites etc.
The SqlMembershipProvider has a facility for counting logged on users, which would mean you probably already have the data sitting in your database if you are using it to manage your forms authentication.
You could also consider having your pages emit an ajax pulse every 'period of time' and count that. or have some applet, silverlight, flash etc doing the same.

Forms authentication - logging out and page history

In my ASP.NET site, when a user clicks logout, I call FormsAuthentication.SignOut and Session.Abandon and redirect them to the login page. This works fine.
However, when I click "back" in the browser I can still see the last page viewed before logout was clicked. When I click on anything I am returned to the logon page as expected.
Is there anyway to expire the page that logout was clicked on so that users never see it when they click back?
Prevent credential and content caching:
First, ensure the forms cookie is not being created sticky:
FormsAuthentication.SetAuthCookie(userName, false);
Next, a little something in the Global.asax to prevent page requests from caching:
public override void Init()
{
base.Init();
BeginRequest += new EventHandler(OnBeginRequest);
}
void OnBeginRequest(object sender, EventArgs e)
{
if (!(Request.Path.EndsWith("Resource.axd")))
{
Response.Cache.SetExpires(DateTime.UtcNow.AddSeconds(-1));
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();
}
}
The combination of the above two approaches has fixed a similar issue in a few apps I've worked on. We intentionally allowed .axd file caching to keep performance impact as minimal as possible - we have heavy use of third party controls that generate axd requests in the background.

What is the best way to show a message to user and redirect to home page when a session times out

I am currently working on a asp.net 3.5 web application which is being used by 500 + concurrent users and the session time-out is set to 24 hours but a recycling of ASPNet process on the server is scheduled to trigger everyday at 3:00 A.M. is causing the session gets timed out.
What is the best way to show a message to user and redirected to home page after session is expired? There are lot of pages in the project, so adding code to every page of the site is not really a good solution.
Thanks in advance
BB
You can use global.asax's session end event to perform your redirect & notification. Just a note, that the session doesn't end when the browser is closed. It ends when the session timeout reached.
void Session_End(Object sender, EventArgs E) {
// Clean up session resources
}

Security considerations for an ASP.Net web application that will be used on a public computer or kiosk

I have an application that can be used without authentication on computers in public locations. It's a simple four page application that allows users to apply for a marriage license. Some offices will have a public computer kiosk where applicants can fill out their own information before proceeding to the clerk. They can also do so at home before visiting the office. What considerations should I take to make sure that a user cannot get access to the previous user's input? Some form data will contain sensitive info such as DOB, SSN and Mother's Maiden Name.
1. Disable AutoComplete
So far, I've set autocomplete=false in my Master page form tag.
<form id="frmMain" runat="server" autocomplete="false">
2. Disable Page Caching
I've also been able to disable page caching in IE and FF, but cannot do so in Safari and Chrome. Anybody know the trick? Hitting the back button still shows the form-filled data in Safari and Chrome.
// Disables page-caching in IE
Response.Cache.SetAllowResponseInBrowserHistory(false);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();
Response.Expires = 0;
// HACK: fixes Firefoxes cache issue
Response.AddHeader("ETag", new Random().Next(1111111, 9999999).ToString());
3. Manage the session
I've also implemented a timer on each page that will kill the session after n number of minutes. The session holds the current application ID with which the pages use to load previously entered data. They can get more time by clicking a button. When the timer is up, it redirects back to the main page where I kill the session in Page_Load. I also redirect to this page when the users click the "Finished/Submit" button. Once the session is killed, navigating to the pages by URL will never load the previous application. It'll be treated as a new one.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
Session.Abandon();
}
4. what else should I do?
Your awesome suggestions/tips here
Since this is a Kiosk app, you'd want to make sure that the browser is configured to honor requests to not cache anything.
Last time I researched the effectiveness of server side no-cache headers, I realized that any one using customized, buggy or uncommon browser might not be honor requests to not cache documents.
You may also want to add javascript back-button breakers on some pages (e.g. some end of session page) and a history navigation deterrent, but not all pages because no one like the back button to be broken.
I think you have the right idea. Killing the session on "finish/submit" is what I would have recommender. Still read over the owasp top 10 and keep your usual vulnerabilities in mind.
1)Make sure you use HTTPS.
2) Always always always test your application for vulnerabilities before rolling it out. I recommend using Wapiti(free), Acunetix($) or NTOSpider($$$$).
3) Keep your server up to date, make sure you run OpenVAS to make sure your server is secure.
Here you are: What should a developer know before building a public web site
Use JavaScript. You will have to capture and prevent each form's submit event, grab the data, submit it via ajax, then use the form's native reset() method. From there you can navigate elsewhere or show validation errors depending on the ajax result. It's easy with jQuery.

Resources