Keep session alive forever as stackoverflow - asp.net-mvc

I need to keep the session live unless until the user clicks logout in my asp.net mvc(C#) application.
When the user closes the browser and opens again, the session should continue with the values.
I am trying to implement as in stackoverflow.
Any ideas/suggestions?

You say you want to keep the session alive "as in StackOverflow."... StackOverflow, like most secure sites, does not keep sessions alive indefinitely. It uses cookies to "remember" the login.

if you use FormsAuthentication, you can do something like:
FormsAuthentication.SetAuthCookie("userName", true);
That will create a cookie that is persisted across different browser sessions, and will achieve what you're looking for.

If you want to remember 'state' even when (because of the expired session / session cookie) you are forcing your users to login again. You need to persist the session data. Perhaps your web-container can do this for you.

First, if you want to make multi-session but temp data, you should probably look into the ASP.NET user profile.
If you want to persist logins across sessions, look at the bits of FormsAuthentication that deal with remembering the user.
If you need to keep sessions alive indefinitely without setting the timeout forever (therefor triggering murder by the server admin in some cases), a neat trick is to setup an Ajax "heartbeat" to ping back to the server while the browser is open and effectively do a "keep this session alive" trick.

The session will be lose when the browser is closed

Related

ASP.net MVC 4 session cookie expires when user closes browser

I had the same issue like this guy. Because I am lucky, his solution also worked for me.
But I think it's a bit dirty and I was wondering if there isn't a better one.
I've set up this configuration on IIS, but the cookies will always expire when the user closes her browser (if I don't use he "cookie hack")
Any Ideas?
EDIT: To clearify: It not the Server side session that is lost, it's only the "ASP.NET_SessionId" cookie lifetime, which is incorrect.
EDIT2: After some Research, I was wondering when the ASP.NET_SessionId cookie is actually set. If I delete it (using Firefox) and refreshing the page (even several times) a new one won't appear ... What's going on here?
EDIT3: I just found out, that the session id cookie will be set if I put something into the session, so that question (EDIT2) is off.
The session cookie will exire as soon as possible for security reasons. One should not extent it's lifetime due to session hijacking.
If you need "the old session back", then use ASP.NET authentication and generate a new session after the users comes back to the site. This will safe memory and also increase overall security.

Security problems with autologin and FormsAuthenticationTicket

Im using autologin on my MVC 3 website.
How do I best handle this problem:
A user signs in at his own computer (and gets a 30 day cookie)
Same user signs in at a friends computer (and gets a 30 day cookie)
Its now possible to autologin in at both computers. The user realizes this and changes his password but his friend is still able to autologin from his computer until the cookie expires.
How do I best handle this?
I could of course set at date on the user when password changed and check this up against the date in the cookie.
Or am I missing something?
I know what you're saying, but I think you're implying an association between the "remember me" function and the "password change" function which in practice, isn't there. The auth token you get when authenticating is not generally tied to the value of the password (i.e. when using the membership provider), after all, you're logically keeping the identity authenticated across sessions and in this regard, it works just fine.
To be honest, this sounds like more of a user behaviour problem than a technology problem. In your use case, someone is consciously asking the browser to allow them to remain authenticated for a long period of time and doing so on a machine which they have no control over. Of course I'm assuming you have a "remember me" checkbox and if you don't, there's your answer right there.
The other thing you might want to look at is what OWASP talks about in part 3 of the Top 10 - Broken authentication and session management. This link will put it in a .NET context for you but in short, it talks a lot about reducing the opportunity for exactly what you're describing to happen by things like eager session expiration, disabling sliding sessions and obviously giving end users the control to expire the token at session expiration and log out at any time.
Don't yo have Remember me checkbox on your login form. The value of this checkbox will dictate whether you are going to create persistent cookie or not. if you don't create persistent cookie, it will expire as soon as session ends. In this scenario you user can leave Remember me checkbox unchecked when logging in on his friends computer. If he doesn't he is calling for trouble himself.

When does the .NET FormAuthentication ticket get checked and how do I tap into this event?

We are attempting to integrate an ASP.NET MVC site with our client's SSO system using PingFederate. I would like to use the built in FormsAuthentication framework to do this. The way I've gone about it so far is:
Set up my Web.config so that my FormsAuthentication LoginURL goes to my site's "BeginAuthentication" action on a "Security" controller. From this action, I set up some session variables (what URL was being accessed, for example, since Ping won't send this info back to me), and then redirect to our client's login page on an external site (www.client.com/Login for example).
From here, the authentication takes place and a cookie is generated on the same domain as the one that our application is running on which contains the unique identifier of the authenticated user, I've set it up so that once this happens, the Ping server will redirect to my "EndAuthentication" action on my "Security" controller.
In this action, I call my membership class's "ValidateUser" method which takes this unique identifier from the cookie and loads in the user on our application that this ID refers to. I save that logged in user in our Session (Session["LoggedInAs"], for example) and expire the cookie that contains the id of the authenticated user that the SSO system provided for me.
All of this works well. The issue I'm wondering about is what happens after our user has already authenticated and manually goes back to our client's login page (www.client.com/login) and logs in as another user. If they do that, then the flow from #2 above to number 3 happens as normal - but since there already exists an authenticated user on our site, it seems as though the FormsAuthentication system doesn't bother kicking off anything so I don't get a chance to check for the cookie I'm looking for to login as this new user. What I'd like to do is, somewhere in my Global.asax file (probably FormsAuthenticate_OnAuthenticate), check to see if the cookie that the SSO system sends to me exists, and if so, sign out of the application using FormsAuthentication.SignOut().
Another issue that seems to be related is that if I let my Session expire, the FormsAuthentication still seems to think I am authenticated and it lets me access a page even though no currently logged in user exists in my Session, so the page doesn't render correctly. Should I tap into the Session_End event and do FormsAuthentication.SignOut() here as well?
Basically, I want to know when the authentication ticket created by
System.Web.Security.FormsAuthentication.SetAuthCookie(..) gets checked in the flow of a request so that I can determine whether I need to SignOut() and force revalidation or not.
Thanks for any help. Sorry for the length of this message, trying to be as detailed as possible.
Mustafa
Welcome to the small section of Hades that is mixing session with formsauth.
If your needs are as complex as presented, you would get more sleep if you implement a full provider stack to share amongst the participating sites. Easier said than done, I know.
But to address your question:
from http://www.codeproject.com/Articles/39026/Exploring-Web-config-system-web-httpModules.aspx
On the way in....Check ticket and set identity #
app.AuthenticateRequest += System.Web.Security.FormsAuthenticationModule.OnEnter-->OnAuthenticate
On the way out... set the ticket and redirect as necessary
app.EndRequest += System.Web.Security.FormsAuthenticationModule.OnLeave
Reflector is your friend. ;-)
I don't know about a specific event for when the cookie is checked, but you could place the appropriate logic in Application_BeginRequest() and check the user's authentication state there.
Another issue that seems to be related
is that if I let my Session expire,
the FormsAuthentication still seems to
think I am authenticated and it lets
me access a page even though no
currently logged in user exists in my
Session, so the page doesn't render
correctly.
The life of the cookie (how long until ASP.NET feels it needs to ask for a password again) and how you are managing state are unrelated. The ASP.NET authentication is cookie based so that, should a developer want to, he could turn off viewstate, session, use no query strings or hidden fields and authentication still works.
If you want to tie the interval at which you request the password to how you are persisting data, then you will want your session expiration to be roughly the same as the cookie expiration, but they will never quite match up. It would be better to have two policies (one for how fast you throw away a users session data and one for how long you are willing to wait before you need to reask for a password)

Handling website access changes when using cookies

If I have a site that uses cookies for authorisation, so when the user returns they don't have to login again.
If for some reason the site admin cancel this users account what is the best way to check for this. I don't want to have to hit the database every time the user visits a page to make sure their account is still live.
So how should I handle this situation?
Several options. Set a shorter expiration on the cookie so they'd have to get authenticated afresh sooner.
Another alternative is to have any important action require that they be authenticated against the database. Thus you would only be hitting the database for more privileged actions that would more likely overlap with the high priority things you'd want a cancelled user be unable to do.

asp.net mvc storing user data

how should I store user data in asp.net mvc? Let's say a user want to see 50 records per page. I wanted to save it in Session, but if I am doing it right, the Session resets every time a new controller is initialized. So where? A cookie?
Typically the session is not reset on controller initialization! Make sure you aren't clearing the session from code.
Anyway, storing this in session cause the record-limit to be reset quite often (depend on the session timeout param).
Consider storing this in the user's profile kept in database (will be used after log in), or in cookie (don't require login to be used). This will keep this setting forever - your users will appreciate that :)
Instead of using the built in ProfileProvider-system in ASP.NET, which you should only use i you want to persist user settings across multiple visits, you could instead put a the settingsdata in the session. Maybe wrapped in a serializable object.
Session is cleared if
you clear it in your code
the cookie storing the sessionid expires (depends on your settings i web.config) (if a
cookie expires during a session, it does not truly expire before the user closes all browser windows)
if the application is restarted (unless you use sticky sessions (DB based sessions) in which case sessiondata persists through application restart)
Session does not reset when a new controller is initialized. But it does when you leave the application (your session ends) or the application is restarted. You should use Profile to store this kind of information.
See this:
http://msdn.microsoft.com/en-us/library/2y3fs9xs.aspx
http://www.odetocode.com/articles/440.aspx

Resources