Session State expiry in ASP.NET - asp.net

I am creating a content management system but there is one problem. What I want to do in my website is that when a user opens the website a new sessionid is created for that user, and when the user closes the website, the sessionid is cleared. How can I can do it?

There isn't a way to detect when a user closes your site or navigates away from your site. After a given period of inactivity (default 20 min), the user's session object will expire and be automatically cleared. I suggest checking out the MSDN article on Session, which will go over your options for tweaking your application's Session.
If on the other hand you're looking to perform custom logic when a user's session begins or expires (due to inactivity), you can add a Global.asax file to your application and use the Session_Start and Session_End methods for that.

That is basically the default behaviour of sessions in ASP.NET.
When a user closes the browser, the non-persistent cookie maintaining the Session ID will be dropped. This wouldn't actually expire the session, but since no reference to it will exist anymore, it will expire automatically within the default 20 minutes. Users revisiting your site after closing the browser window would have to use a new session. (Source)

An easy solution which works independently of Asp.net is to put timestamps on your session data and delete expired entries periodically.

Related

Forms Authentication on browser exit

This morning me and my co-worker went on discussion about storing auth cookie when
RememberMe = false.
MVC4 , Forms Authentocation, C#.Net, Visual Studio 2012, IIS 7.5 , InProcess Session
User LogsIn,(RememberMe = false) and Navigates to an item in the app.Default session timeOut was set 30 mins,
User Copied the URL and Closed the browser(IE9)
Opened new browser(IE9) and Pasted the Copied URL, UI redirected to loginPage.
Here I say session created in step 1 is still valid., On close of the browser , browser lost the AuthCookie.
He says that that Session is created based on browser session also. I'm bit confused.
Please let me know what actually happened.
Sorry for the bad English
RememberMe = false means the authentication cookie that was issued to the user was NOT persistent (the expiration of the cookie is set to "SESSION"). That is, the cookie is lost when the browser session ends. RememberMe = true means a persistent cookie is created and is saved across multiple browser sessions(the expiration of the cookie is set to a specific date, usually configured in web.config).
Read the documentation here
I'm assuming you're using the default Session-State Mode, which is InProc. A session generates a SessionID and this ID is stored in a cookie. This cookie is sent to the user and whilst requests are made with that cookie, the session is alive. The ID itself identifies the unique browser, which is why you can log into the same website with different accounts when you use two different browsers at the same time. However, you can't sign into different accounts from different tabs of the same browser (unless the website has specifically customised their site to support that feature).
By closing the browser, this cookie is deleted, and so the session will be ended when its timeout period has been reached. The reason you're taken to the UI page is because the new cookie you have no longer has the same session ID so, for all intents and purposes, you're a new user.

Asp.net destroy session by sessionid

When one user login my site, this user have a session[sessionid like:xxxx-xxxx-xxxx-xx], when he login again elsewhere, he have a different session[sessionid like:yyyy-yyyy-yy-yyy], HOW CAN I DESTROPY THE PREVIOUS SESSION[sessionid like:xxxx-xxxx-xxxx-xx],after he login again with session[sessionid like:yyyy-yyyy-yy-yyy].
Destroy one session in another sesson!
Is this possible?
Thanks a lot!
There seems to be a lot of confusion regarding this request. I believe this individual wants to know how to prevent concurrent user sessions.
The proposed method: When a user logs in successfully, make this new user sessions active and abandon any other existing active sessions for the user.
My solution:
Upon Login, save the SessionID to a database, referenced to the user's account
In the Site Master file (or any file you may share with all the pages of your site), compare the current SessionID (HttpContext.Current.Session.SessionID) with the Saved SessionID.
If the two do not match, Abandon the session (Session.Abandon).
It's a simple solution, but it should address the issue.
don't worry about that, if you should worry it means your app design is bad.
put a logger in the Global.asax in the Session_End event and you will be able to track when unused sessions are closed by reading the log file.

How to tackle this session problem in ASP.NET,VB.NET?

How to tackle this session problem in ASP.NET,VB.NET?
The following requirement are there:
When the authorized user logs into the system that user is not allowed to login from another computer or in different browser other than that user is using right at this time.
The remedy we applied was: We have kept "Is_Loggedin" as a column with data type "bit" in a mst_vendor as a table name. When a user logs in we set the flag, Is_Loggedin, to "1" and each time when someone tries to log in using this account, the system is showing the error "The user is already logged in.".
When the user logs out it turns to "0" as the logout procedure calls as soon as the user clicks the log out button.
Problem scenario:
When the user closes the browser the flag remains the same, that is, "1".
When power gets off, it remains the same as "1".
If the session timeouts after a predefined value it remains the same.
There may be different scenarios other than this.
Is there any way so that we can store this internal flagging for the user's login status using the application object?
It may improve efficiency of the system and also eliminates the above problematic scenarios.
You should use the Global.asax file and use the Session_End function.
Session_End: Fired when a user's session times out, ends, or they leave the application Web site.
Store a datetime as another column next to the bit, and update it each and every time the user requests a page.
When a new user comes along with the same credentials and the bit is "1" you can check the datetime, and if it was a while ago you can be certain the user is no longer there. So let the login go ahead.
You could keep a pulse going in script, and when the pulse times out, consider the user finished with that session.
The benefit to this is that you can tell the difference between the user sitting idle on the site and the user leaving the site.
From a very top level view, here is what you can do
Use Cache with SlidingExpiration.
Everytime a user attempts login, check the cache with his username as the key. If an entry exists in the cache, you can say that user is already logged in and deny login.
If the key is not found, allow login and create a new key in the cache as the username and set the sliding expiration time. (This should be carefully chosen as this would be the duration, the user wouldnt be locked out after the browser is closed and user attempts to relogin.)
In the Application_PreRequestHandlerExecute handler in Global, check if the user is currently active (you can use sessions for this), reset the sliding expiration time for the user. This way, with each page request the cache expiration time would be reset.
If the user closes the browser and moves off, the cache would expire after the set period of time, and would free the user to log in again.
if in case the user attempts to login again before the cache expires, the user would have to wait for some time to let the cache expire.
if the user logs off properly, you can remove the cache entry on the logoff event such that user doesnt have to wait to relogin.
The Sliding expiration timeout can be synced with session timeout to emulate the actual session timeout for the application.
With this approach, you would also save on a lot of database round trips to update/check the user status and this would work irrespective of the hosting enviornment or the session modes.
Yeah, a script would be a good idea. Just set the session timeout to be 5 minutes instead of 20 and then write a method into session.end in the global.asax file that updates the database accordingly.

How does gmail keep a user logged in?

I wonder how gmail/Google keeps a user logged in even across sessions. And how (e.g. cookies) and what (e.g. time) do they use to decide to re-prompt the user for the login?
The short answer is that cookies do not have to expire when you close down the broweser or the machine they are on. Depending on constraints configured in the browser, if the server sets an expiry date in the future, the browser will continue to present the cookie until that expiry time.
C.
Well cookies are stored in your local machine, you can see those in totals -content settings -cookies.You can clear the cookies as well.So your information is stored there.More over about the sessions if they have been implemented on the websites...They could be destroyed by two methods ,one is by giving the time for session to expire the another way is when you forcefully want to expire the session then session abandon method is used.You must have seen sometimes if you don't scroll through a page for some time, then its written there your session has been expired. Sessions are executed on the server side and there values can be stored on the client side in the cookies as well.
Hope it would help you to understand William

Dealing with expired authentication for a partially filled form?

I have a large webform, and would like to prompt the user to login if their session expires, or have them login when they submit the form. It seems that having them login when they submit the form creates alot of challenges because they get redirected to the login page and then the postback data for the original form submission is lost.
So I'm thinking about how to prompt them to login asynchrounsly when the session expires. So that they stay on the original form page, have a panel appear telling them the session has expired and they need to login, it submits the login asynchronously, the login panel disapears, and the user is still on the original partially filled form and can submit it. Is this easily doable using the existing ASP.NET Membership controls? When they submit the form will I need to worry about the session key? I mean, I am wondering if the session key the form submits will be the original one from before the session expired which won't match the new one generated after logging in again asynchrounously(I still do not understand the details of how ASP.NET tracks authentication/session IDs).
Edit: Yes I am actually concerned about authentication expiration. The user must be authenticated for the submitted data to be considered valid.
Session expiration is different than authentication expiration - you probably need to determine which you are concerned about.
Sessions expire after 20 minutes of inactivity (by default), and will clear the Session object. When it expires, anything you stashed into Session will be gone.
[Forms] Authentication expires after 30 minutes of inactivity (by default) - though it's only updated every half-life. So, in reality - it can expire after 15 minutes of inactivity (by default). When it expires, the next request will be redirected to your login page.
Session and Authentication aren't really related - you can be an anonymous (non-authenticated) user, and still have a Session - or you can be logged-in (authenticated) but not have a Session. Your Session could expire before your authentication does, or vice-versa.
You could simply crank up the values for expiration for Session and/or Authentication. The problem with Session is that it chews server resources, and keeping Authentication is a security problem.
If you're just concerned about keeping them both alive for the duration of your form, a small bit of JavaScript that hits a server page with XmlHttpRequest or an iframe will reset the expiration for both (because of slidingExpiration).
There's other techniques as well, but it'd be helpful to better define the issue first.
Very nice response #Mark Brackett reading the OP's comment below I believe this is his end goal.
On the button / submit element you want to write a javascript method that via ajax will poll the server to see if they are still authenticated.
If they are auth'd still you want to return true and let the form do it's regular submission, if it returns false you want to not allow the form to submit. At this point you will want to use javascript to display either a "window" inside the browser (think floating div) or to pop up a true new window for them to log in (I'd recommend the first method) that this new window will allow them to login via ajax and then hide/close itself.
Then with that window gone when they click the submit button again they will be able to successfully post the form.
There are many ways of doing this: you may store a cookie on the user's computer, or you can also split the form into smaller forms (i.e.: step 1 - enter your personal information, step 2 - enter billing info, etc.).
Splitting your form makes it faster for a user to enter the data, thus reducing the chances for their session to expire.
Adding a cookie to this makes it so that the person's information is still there, even if you log in afterwards. Just make sure to unset these said cookies at the end.

Resources