Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where is the Session Stored in Rails?

In Rails, I have implemented the below code for user auth (confirmed to be correct). However, I wanted to confirm my thinking for this strange session[:session_token]. is this the "cookie" that is stored in the browser?

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception

  helper_method :current_user, :signed_in?

  private
  def current_user
    @current_user ||= User.find_by_session_token(session[:session_token])
  end

  def signed_in?
    !!current_user
  end

  def sign_in(user)
    @current_user = user
    session[:session_token] = user.reset_token!
  end

  def sign_out
    current_user.try(:reset_token!)
    session[:session_token] = nil
  end

  def require_signed_in!
    redirect_to new_session_url unless signed_in?
  end
end 

My understanding so far of how this works is that whenever the browser/client sends a request to rails, the cookie (with the session[:session_token]) is also sent over, thus allowing the current_user method to find the user. Is my understanding correct? This is strange to me because there's a gap of knowledge of how exactly the browser/client gets access to the session cookie when we declare it in ApplicationController (Rails-side).

like image 605
fibono Avatar asked Jul 13 '15 00:07

fibono


People also ask

Where does Rails store session data?

In Rails, session object is sent back and forth inside cookies. When you set session[:user_id] = 3 inside of your controller action, the response sent from that action will have a header Set-Cookie: my-session-cookie .

How are sessions stored in Rails?

Rails will create a new record in your sessions table with a random session ID (say, 09497d46978bf6f32265fefb5cc52264 ). It'll store {current_user_id: 1} (Base64-encoded) in the data attribute of that record. And it'll return the generated session ID, 09497d46978bf6f32265fefb5cc52264 , to the browser using Set-Cookie .

Where is session stored?

A session is a global variable stored on the server. Each session is assigned a unique id which is used to retrieve stored values. Whenever a session is created, a cookie containing the unique session id is stored on the user's computer and returned with every request to the server.

Is session stored on client or server?

The session data is stored on the server, but it also stores an id string in a cookie to identify the user.


2 Answers

You are pretty much there. Although, I have a feeling you might be confusing apples with oranges...

Sessions:

Very often in dynamic web sites one would want to store user data between HTTP requests (because http is stateless and you can't otherwise associate a request to any other request), but you don't want that data to be readable and/or editable on the client-side inside of the URL (like.. yourwebsite.com/yourPage?cookie=12345&id=678), and so on..., because you don't want the client to play around with that data without passing through your server-side code.

One way to solve this problem is to store that data server-side, give it a "session_token"(as you called it), and let the client only know (and pass back at every http request) that token. This is how the session is implemented.

Cookies:

The most common technique for implementing sessions in Rails involve using cookies, which are small pieces of text placed on the user’s browser. Because cookies persist from one page to the next, they can store information (such as a session_token or whatever else you want) that can be used by the application to retrieve the logged-in user from the database.

Where is the Session Stored in Rails?

Using both of the above concepts I can now tell you that the default session store inside of Rails is CookieStore, which is about 4KB in size.

To put it simply...

def sign_in(user)
  @current_user = user
  session[:session_token] = user.reset_token!
end

...method that you defined places the user into a temporary session.

Then the idea is that the following...

def current_user
  @current_user ||= User.find_by_session_token(session[:session_token])
end

...method would find and retrieve the user from the database corresponding to the session token and initialize it to a variable you specified.

Additional info:

You should also note that there is an important difference between Rails's session and cookies helper methods...

They both generate cookies, however, session[...] method generates temporary cookies, which should expire upon the browser exit, and cookies[...] method creates persistent cookies, which do not.

Additionally, I would suggest having a look at Section 2 of Ruby on Rails Security guide. You might find it useful.

Hope this helps you out.

like image 190
Timur Mamedov Avatar answered Oct 14 '22 09:10

Timur Mamedov


  • Session is stored in server side. And,
  • Cookie is stored in client side (in browser cookie). And,
  • When client/browser send a request to rails server, every time cookies are sent to rails server.

When a session is set in rails server, like: session[:user_id] = 4,

  • Rails store it in server side.
  • Session is saved in server side like key value pair (like json object)

For each browser, Rails set a session identifier in cookie, so that, Rails can find the correct session information for a request.

Without session identifier in cookie, Rails do not know, what session belongs to what browser. So, session will not work without cookie.

Edit: Explain: sessions are stored server side

Suppose, I am using your web application, and after login I will be redirected to home page.

I open login page, input username and password, and click login button.

The form is submitted to sessions#login action.

in sessions#login - you check username and password - and set session[:session_token]:

if username and password is correct
  random_unique_identifier_string = @user.remember_token
  session[:session_token] = random_unique_identifier_string
  redirect_to root_url
end

When server run this code session[:session_token], server need an unique identifier for each browser session.

So, server generate an unique identifier for this browser, such as: abc123

  1. Server set all session variables in a place (may be in some folder or in database), label this folder as abc123.

  2. Now server send a cookie request to browser - to set cookie _ebook_session = abc123. (I see, if my app name is ebook, in rails, cookie name is like: _ebook_session)

  3. Now the page redirect to home page.

** Note: Everything above happen in single request **

Now, in my browser, I want to open some page that need authentication (suppose, dashboard page).

You added before_action: require_signed_in! in dashboard controller.

So, when I open dashboard page in my browser, browser by default send all cookies with every request. so _ebook_session cookie is sent to server. Your server gets the value of _ebook_session cookie is abc123. Now your application know we need to look in abc123 folder for session. Now you can get value of session[:session_token] from abc123 folder.

** I have explained second request above **

Each browser needs unique session identifier.

Important: _ebook_session cookie will be set in browser in first request. If we already have _ebook_session cookie set in a browser, we do not need to set it again, second, third and next requests in that specific browser.

I hope, you understand.

like image 1
mahfuz Avatar answered Oct 14 '22 10:10

mahfuz