asp.net mvc storing user data - asp.net-mvc

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

Related

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.

How to track a user's session without requiring them to login with ruby on rails

I have an application that has an actual map of objects that any visitor can view as long as they have the correct access code. I don't require the user to login because I don't want to make them create an account as it is unnecessary. I want to allow the users to mark the objects on the map with a check and save the edits within the session. So if the user refreshed the page or they close the application and reopen it an hour or so later, I would like to save their marks based off their session id. But I am confused on how to set this up without requiring them to login because I am unsure how the sessions would work.
Any help would be greatly appreciated!
Sessions in Rails work the exact same way regardless if you have a proper authentication system or not.
When a first time visitor visits your application the sessions middleware creates a session identifier. This is a cryptographic hash that is kept by the server and also passed to the user in a cookie.
This lets you identify users across requests.
This session identifier is also linked to a session storage. By default this is ActionDispatch::Session::CookieStore which lets you store session data in a encrypted cookie held by the client. This is where you would normally store a user id. Since its a cookie the amount of storage space is very limited. If you want to store more data in the session you can use a different store such as Memcached, Redis or ActiveRecord.
But what you may want to consider is creating (guest) user records implicitly without the normal sign up procedure. I would just use Warden and have a bare bones user model and a cron tab that cleans out unneeded data periodically.
This gives you a database oriented application model where you can use associations and build it like a standard rails application instead of the untestable mess that results when someone goes bonkers with sessions.
I would implement Cookies (with their permission of course). You can store basic data in it, or even create a sort of ID for them so when they return you can restore their settings

Using session while sending set of AJAX requests

In my Rails application I make set of AJAX calls at once and that causes sending the same session cookie for each request.
The problem is that rails sets new session cookie in every response and therefore it expects that cookie value in the request after.
I'm looking for server-side solution because I don't want to chain those requests (they are time consuming).
Is it possible to change this behavior? And what security risks would come with it?
(I'm using Rails 4.1.0)
Many thanks
If the user doesn't already have a session cookie then there is nothing you can do.
If you can guarantee that the user already has a session (for example, if you require users to be logged in) then you may be able to do this with a server side session store.
With a server side session store the session cookie just contains an identifier - even if your overlapping ajax requests change values in the session they will not change the session cookie. In general this is better security wise: for example, old sessions can't be replayed after the user has logged out. Rails switched to the cookie store by default for performance reasons: no external data store needs to be accessed (however it does slightly increase the amount of data sent on each request)
Switching to a serverside session store isn't enough though and still leaves you open to race conditions. It is very easy to end up with a sequence along the lines of
Request A loads session
Request B loads session
Request B completes, saves session
Request A saves session and overwrites the session changes made by B
You need a session store that will attempt to merge any changes it has made with any changes that may have occurred from other requests.
I wrote such a session store some time ago. I haven't updated it for rails 4, since it isn't something i need anymore but you may be able to (or at least find inspiration in it)

Rails v2.3 : Difference between session and cookies

I am learning Rails by reading the online guide(for Rails v2.3). The guide is great, however, there is a confusion for me, that's:
there is a chapter explains the Session of Rails and another chapter explains Cookies of Rails. The explanation is easy to understand separately, but when compare the two, reader like me does not see the significant difference between Session and Cookies . Especially under which situation session should be used and under which situation Cookies should be used ?
Besides, in the session chapter, there is a concept of CookieStore , what is the difference between the CookieStore and Cookies then?
Could someone explain to me these?
Sessions & Cookies both hold the ability to store some information (e.g : the current_user id) in between two or more requests which (in http) are otherwise stateless.
But Session is more of an abstract concept related to the notion of being in a certain state for a specific amount of time : the info it contains can be stored in the database, in a server side file, in a redis hash OR in a cookie.
Cookies are always the little text file navigators have to store some persistent data in between requests... But having some data on the client side can be insecure so that's why it is often encrypted. But it's true the notion can overlap with session.
TL;DR : session the abstract concept of holding temporary data. Cookies one (common) way of doing it.
A cookie is a small text file stored in the browser.
A session is the concept of a state of being "in-use", and that state can have data associated with it. Rails keeps track of sessions with cookies, and lets you choose different storage for associated data and access it with the same session interface.
CookieStore means all the session information is stored inside the cookie itself. You can choose to use various other stores where appropriate, and it'll still be available with your session accessor methods.
In addition to the session, you can set other cookies to store information on the user's browser. These are not tied to the session and can be set, accessed and deleted independently.
Example 1, storing a logged-in user's shopping cart in a session:
session[:embarassing_products] = ['ooh',
'naughty',
'lucky_im_using_activerecord_store',
'only_the_session_id_is_in_the_cookie',
'other_data_arent_in_the_browser']
The shopping cart is preserved for the user's session. You can set the session to end when the browser window is closed, when the user logs out, or when a certain amount of time passes.
Example 2, remembering a browser's last language preference for your domain in a cookie:
cookie[:lang] = 'en-US'
This information is stored inside the cookie itself. Unless the cookie expires or is deleted (by you or the user), it stays inside the browser.
As to me the main difference is that the session data stored on the server, whereas the cookies are stored on the client (browser).
So you can trust the data from the session. Information from the cookie can be manipulated, stolen, and thus should not be relied on for critical use (for right access for example).
Second point, is that cookies have a limited size, and are only text-based. You can store in session many complex objects (but beware of memory consumpation), and you don't have to transfer them to client then back at each request.
And typically the session only persists until the user shuts down their browser. That's useful for typical logins. Whereas if you needed information to persist between sessions you could use a cookie with a longer duration, for example a 'remember me' flag that persists even after the browser is restarted.

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