Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 37 ยท Authentication and Security

Sessions, Cookies and the Current User

Learn how Rails sessions and cookies keep users logged in, how encrypted cookie sessions work, flash messages, remember-me cookies, current_user helpers, before_action guards and secure cookie settings.

HTTP has no memory. Each request arrives as a stranger: the server answers, forgets, and the next request knows nothing about the last. To keep a user logged in, to remember a shopping cart or to show "Saved!" after a redirect, the app needs a small piece of state that the browser sends back every time. That is the job of cookies, and Rails builds the session and the flash on top of them.

This lesson explains how Rails stores session data, how login state works, how to write guards like require_login, and which cookie settings matter for security. Real Rails code is read-only on this page; the runnable stand-ins use Ruby's own OpenSSL to show signing and encryption. Passwords and hashing were covered in authentication with has_secure_password.

Cookies in two minutes

A server sets a cookie with a response header: Set-Cookie: theme=dark; Path=/; Secure; HttpOnly; SameSite=Lax. The browser stores it and sends Cookie: theme=dark on later requests to that site. Cookies are small (about 4 KB), belong to the user and can be edited by the user, so never trust a plain cookie.

Rails gives you the cookies object:

Ruby
cookies[:theme] = "dark"                                   # plain, user can read and change it
cookies.signed[:user_id] = 7                               # readable, but tamper-proof
cookies.encrypted[:prefs] = { lang: "en" }                 # unreadable and tamper-proof
cookies[:visit] = { value: "1", expires: 1.year, httponly: true, secure: true, same_site: :lax }
cookies.permanent.signed[:remember] = user.id
cookies.delete(:theme)
  • signed adds an HMAC (a keyed fingerprint). The user can see the value but cannot change it without detection.
  • encrypted hides the value as well. Rails' session cookie is encrypted.
Ruby Stand-in: signed versus encrypted cookie

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

That is the essence of Rails cookies: Rails derives keys from secret_key_base (kept in credentials) and uses the same techniques.

The session

session looks like a hash that lasts across requests:

Ruby
session[:user_id] = user.id
session[:cart] = { 3 => 2 }
session.delete(:cart)
reset_session            # drop everything and issue a new session

By default Rails stores the whole session inside one encrypted cookie (_myapp_session). Advantages: no server storage and it scales; limits: about 4 KB, and the data lives with the client, so keep it small (an id, never a whole record) and do not store secrets you would not want a user to replay. If a session cookie is stolen, whoever holds it is that user, because it is valid until it expires. Sessions can also live in the database or Redis (config.session_store :cache_store), which lets you revoke them, and the Rails 8 authentication generator keeps a sessions table for this reason.

Never put objects in the session; store ids (session[:user_id]) and load the record per request.

The flash

The flash is a session value that survives exactly one more request. It is perfect for "Post saved" after a redirect:

Ruby
redirect_to @post, notice: "Post saved"
redirect_to root_path, alert: "Please sign in"
flash[:warning] = "Almost out of space"
flash.now[:alert] = "Fix the errors"      # for the current render, no redirect

Show it in the layout:

ERB
<% flash.each do |type, message| %>
  <div class="flash <%= type %>"><%= message %></div>
<% end %>
Ruby Stand-in: a flash that lives one request

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Current user and guards

Put login logic in ApplicationController so every controller can use it:

Ruby
class ApplicationController < ActionController::Base
  before_action :require_login
  helper_method :current_user, :logged_in?

  private

  def current_user
    @current_user ||= User.find_by(id: session[:user_id])
  end

  def logged_in? = current_user.present?

  def require_login
    return if logged_in?
    session[:return_to] = request.fullpath if request.get?
    redirect_to new_session_path, alert: "Please sign in"
  end
end

class PagesController < ApplicationController
  skip_before_action :require_login, only: %i[home about]
end

before_action runs before every action; a redirect inside it halts the request. helper_method makes current_user available in views. Memoizing with ||= means one query per request.

The "secure by default" approach (everything requires login, a few pages opt out with skip_before_action) is safer than the opposite, because a forgotten controller is private instead of public. After login, redirect to session.delete(:return_to) || root_path. Only accept local paths there, or you create an open-redirect hole.

Remember me

A session cookie normally dies with the browser. For "remember me", set a long-lived cookie with a random token, and store only a hash of the token in the database so a leaked table cannot be replayed:

Ruby
def remember(user)
  token = SecureRandom.urlsafe_base64(32)
  user.update!(remember_digest: Digest::SHA256.hexdigest(token))
  cookies.permanent.encrypted[:remember] = { value: [user.id, token], httponly: true, secure: Rails.env.production? }
end

Rotate the token on every login and delete it at logout.

Flag Effect
HttpOnly JavaScript cannot read the cookie, so an XSS bug cannot steal it. Rails session cookies are HttpOnly.
Secure Only sent over HTTPS (config.force_ssl = true sets it).
SameSite=Lax Not sent on cross-site sub-requests, a defence against CSRF. Rails defaults to Lax.
expires A fixed end date; omit it for a browser-session cookie.

Rotate secret_key_base and never commit it; it lives in config/credentials.yml.enc (see deployment). Also add config.session_store :cookie_store, expire_after: 14.days for an idle timeout.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the default Rails session store contain?

    The cookie store serialises and encrypts the session into one cookie, so no server storage is required.
  2. 2. What is the difference between a signed and an encrypted cookie?

    A signature detects changes; encryption additionally hides the contents.
  3. 3. How long does a flash value live?

    Flash entries are available in the following request and then discarded; flash.now is for the current render.
  4. 4. Which cookie attribute stops JavaScript from reading the cookie?

    HttpOnly hides the cookie from document.cookie, limiting the damage of an XSS bug.

Summary

  • Cookies carry state; never trust a plain cookie. Use signed or encrypted.
  • The Rails session lives in one encrypted cookie by default; keep ids, not objects, in it.
  • The flash survives one redirect; flash.now is for the current render.
  • Centralise current_user and require_login in ApplicationController, and opt public pages out.
  • Use HttpOnly, Secure and SameSite, force HTTPS, and protect secret_key_base.

Next: Web security and authorization