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

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.

Related

Missing ASP.Net cookies from iOS

I'm experiencing some trouble with an ASP.NET MVC 5 application that has been buggering me for a few days.
The application is using Forms Authentication to control whether a user is Authenticated, and Session to keep track of the user's data.
A few of our users are unable to log in, and I have been able to recreate the problem on a collegue's device. We don't know much about the devices with the problems, except that they all seem to be running iOS. I can't seem to nail down the pattern, though, as one user who reported the problem was running 11.2.5, which I am also running myself without trouble. The collegue's device is running 11.3 beta, but I haven't yet heard of any other users with this version, so I'm unable to pin point that as the problem - which also seems unlikely when one of the users with the problem is running 11.2.5.
The issue happens after the users try logging in. After a successful login, the user is redirected to a specific section of the site, where Authentication is required. Requesting any page in this section redirects you to the login page if you are not Authenticated.
Some of the resources that are requested on this page expect to retrieve some data from Session. For some reason, the Session cookie may sometimes be missing, and other times the Authorization cookie is missing.
For the past few days while I have been hunting this, my collegue's device happened to leave out the Session cookie when requesting our Cachemanifest, in which we expect to be able to generate a specific part based on some data from the Session. This caused the generation to fail, which in turn caused the request to fail.
After changing the generation logic to work around this, with a different solution if the Session cookie is missing, my collegue's device has changed its approach; Now, it includes the Session cookie when requesting this resource, but instead leaves out the Authorization cookie in a subsequent request to a different resource, which is still in the section that requires Authorization. This resource happens to be mentioned in the Cachemanifest, and because this next request does not include the Authorizaiton cookie, that request is redirected to the login page, which is interpreted by the Cachemanifest as an error.
As far as I recall, I haven't changed anything else, so I'm really at a loss as to why this devices' behaviour has changed.
Both of these cookies are included in other requests before and after the failing request, and there doesn't seem to be a pattern between what requests is chooses to leave these two cookies out of, or which cookies to leave out. The only thing that is consistent is that the behaviour doesn't change when retrying after clearing the browser data (only after I made my change, which I still don't see how could result in this behaviour).
The site is forcing HTTPS, so I tried setting the Session cookie to Secure, but that didn't seem to make a difference.
I still need to try setting the Authorization cookie to Secure, but I'm not very optimistic there. I also still need to try reverting my changes to see if the old behaviour reappears.
Has anybody experienced similar problems before, or does anybody have any further suggestions? I know I might be a bit sparse on the details, I'd be happy to provide any further details if I'm able.
Thank you in advance :)

Rails 5 session.delete, not deleting cookies in my browser

I've been doing the exercise in
https://www.railstutorial.org/book/basic_login#sec-exercises_logging_out
It's says that I should confirm that the session is deleted after logging out,
Does deleting the session using
session.delete(:user_id)
will make the cookie in my browser (Firefox), disappear?
Also, I've noticed that the content of the cookie changes when I'm visiting different pages in my website, is that an intended behavior? I also get cookies when visiting my website, for the first time, even when not logging on
No, it will simply remove the key from the cookie as we can see in the source code https://github.com/rails/rails/blob/master/actionpack/lib/action_dispatch/request/session.rb#L146.
It will in effect kill the authenticated but the cookie will still be there (it just won't say the user is authenticated anymore).
Also, I've noticed that the content of the cookie changes when I'm visiting different pages in my website, is that an intended behavior?
Yes, if you're using CookieStore (which is the default way in Rails) all the data is stored on the cookie. So if you add or change fields, the cookie changes . (You will notice that the data is encrypted so this is secure). http://api.rubyonrails.org/classes/ActionDispatch/Session/CookieStore.html
I also get cookies when visiting my website, for the first time, even
when not logging on
It makes sense that Rails starts the session even before any authentication is happening - it's basically just an identifier without any data any it yet. A "Session" doesn't have to mean an authenticated user, you might want to save the user's preferred language or the time he opened the website even before he's authenticated.

ASP.NET MVC Cookie gets deleted after redirect to action

I am working on an ASP.NET MVC 4 application. I have created few cookies and did not set any expiration time on it. When I am doing a RedirectToAction, all the cookies are getting deleted. I am not sure what I am missing here. Following is the code I wrote to create and access cookies:
Creating cookies:
HttpCookie authorizedCookie = new HttpCookie(AuthCookieName);
authorizedCookie.Value = authorized.ToString();
Response.SetCookie(authorizedCookie);
Accessing Cookies:
authorized = Request.Cookies[AuthCookieName] != null ? System.Convert.ToBoolean(Request.Cookies[AuthCookieName].Value) : false;
When I am trying to access the cookies, the cookie collection is always empty.
Update:
I have also tried setting the domain, expiration time, httponly and yet nothing seems to work. When I look at fiddler, the cookies just seems to be deleted immediately after the redirect.
Response.SetCookie() only updates existing cookies. Use Response.Cookies.Add().
I am able to create the cookies now. The issue seems to be with my IE settings. I reset the browser to its initial state and the cookies are working fine.
I am still not sure which setting was causing the issue. Because of this I am still not convinced to use the cookie approach. Currently my website is heavily dependent on cookies and any issues with the user's browser will render my website useless. I am planning to replace the cookie approach.
Thanks for all your responses.

Should the SessionID in the QueryString or the Cookie of a GET request take precedence?

If I receive a request to the url host.com/site-directory/page-slug.html?session={someValidNonExpiredSessionGuid} and I detect a session cookie with the value: {someOtherValidNonExpiredSessionGuid}, then
Which session is the correct session to associate with the request?
Here's some background:
The pattern I am using for maintaining state across HTTP requests is to store a unique ID in the querystring, form collection and/or cookie. Then, on each request, I locate the unique Id and pull date from a database table. If the id is not valid, or the session is expired, a new session will be created (with a new id, a new cookie, etc).
The default behavior is that all forms will have a field:
<input type="hidden" name="session" value="{someGuid}" />
All links to other pages on the site will have an appended querystring parameter
a sample link
And, if the user's browsing device supports cookies, a cookie will be set having the session's value.
If I have validated that the user's browsing device supports cookies, then my form and querystring will no longer require the the session id field/parameter.
However, I am having a conceptual issue in deciding whether the session parameter of the querystring should take precedence over the cookie value or vice-versa. It seems like I could potentially get bad data in either circumstance. I could get data with a bad querystring parameter if the user bookmarked a page with the session parameter included in the URL. I could also get bad data from the cookie, if a user closes the browser without terminating the session, and the session expire-window has not yet closed. It also seems like both options could be vulnerable to a malicious user intercepting the request and sending a request with the same session information.
So, once again, my question is
If I receive a request to the url host.com/site-directory/page-slug.html?session={someValidNonExpiredSessionGuid} and I detect a session cookie with the value: {someOtherValidNonExpiredSessionGuid}, then Which session is the correct session to associate with the request?
I am leaning towards the cookie session, because it seems like the most common scenario will be a bookmark with the session included. I've already decided that the form post data should take the greatest precedence, because a page will always render the form with the correct ID, and the only possible situation with a wrong, non-expired ID is a very quickly implemented XSS attack, which is circumvented by including a request-scoped anti-forgery token field.
In addition to the primary question I appreciate any insight to any security-related or logical oversights I have expressed in this description. I apologize for the long post, but felt it was necessary to explain the situation. Thank you very much for your input.
Also, it is not necessarily relevant to the question, but I am using ASP.NET MVC in most situations, and setting my cookies manually with Response.Cookies.
From a security standpoint sessions should not be stored in query strings.
For example:
If sessions are stored in queries and you link to a remote host on the same page, the users valid session could be sent to the remote host via the referer header.
Sessions should always be stored in cookies.
You should try to store it in the cookie (looking the the browser caps to see if the browser supports cookies) and then have a fall back for query string.
I too would lean towards using the cookie session ID in case of ambiguity. This primarily because I'd trust the cookie implementation to be more well baked, more well tested, and more idiot-proof than my own home brewed session tracking implementation. For e.g. there are cases where ASP.NET automatically knows to clear the session cookies, renew them etc.
Also, I would design it so the cookies aren't persistent to minimize the edge cases. If the user closes the browser, then the session is closed.
The other simplification I would consider is to have either cookies or URL based tracking and not both. If the browser supports cookies, there is really no reason to also track the session through a URL.
Thoughts?
Curious ... What were your reason to rule out using the stock ASP.NET cookieless session implementation? - http://msdn.microsoft.com/en-us/library/aa479314.aspx#cookieless_topic2
If I receive a request to the url
host.com/site-directory/page-slug.html?session={someValidNonExpiredSessionGuid}
and I detect a session cookie with the
value:
{someOtherValidNonExpiredSessionGuid},
then Which session is the correct
session to associate with the request?
To answer your specific question, I'd recommend putting session management in the cookies as opposed to the querystring. As has been mentioned, cookies can be set to expire whereas the querystring cannot. This allows your thin-clients to assist in their own session maintenance by removing their own expired cookies. Moreover, since cookies are dropped to specific browsers, you reduce the chances of another browser spoofing the original browser session.
The only way I would use the querystring to pass session information would be as a backup method to re-establish a browser session onto a new browser instance. Here's a scenario: you have an active session using browser A on machine A which suffers some catastrophic error. You want a way to re-establish that same session on another browser instance on either the same machine or on another machine. If your code-behind can recognize that the session cookie doesn't exist, but that a valid session id exists in the querystring, you could initiate a challenge-response to verify the integrity of that session id and then drop a new session cookie on the new machine. Kinda extreme in my humble opinion, but the functionality might be useful in certain situations.
ADDED: I understand that you may want to accommodate users who have turned cookies off on their browsers, and while you can use the querystring to hold the session id I'd recommend against it. But if you must, encrypt that sucker using browser-machine specific information.

Keep session alive forever as stackoverflow

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

Resources