Session-based authentication helps websites remember who you are after you log in. It keeps you signed in while you browse.
Session-based authentication in Ruby on Rails
class SessionsController < ApplicationController def create user = User.find_by(email: params[:email]) if user&.authenticate(params[:password]) session[:user_id] = user.id redirect_to root_path, notice: 'Logged in successfully' else flash.now[:alert] = 'Invalid email or password' render :new end end def destroy session.delete(:user_id) redirect_to root_path, notice: 'Logged out successfully' end end
Use session[:key] to store or access session data.
Sessions are stored on the server, and the browser keeps a cookie to identify the session.
session[:user_id] = user.id
session.delete(:user_id)
current_user = User.find_by(id: session[:user_id])
This example shows a simple session-based login system. The SessionsController handles logging in and out. The ApplicationController has a helper method to get the current user and a method to protect pages that need login.
class SessionsController < ApplicationController def new # Shows login form end def create user = User.find_by(email: params[:email]) if user&.authenticate(params[:password]) session[:user_id] = user.id redirect_to root_path, notice: 'Logged in successfully' else flash.now[:alert] = 'Invalid email or password' render :new end end def destroy session.delete(:user_id) redirect_to root_path, notice: 'Logged out successfully' end end class ApplicationController < ActionController::Base helper_method :current_user def current_user @current_user ||= User.find_by(id: session[:user_id]) end def authenticate_user! redirect_to login_path, alert: 'Please log in' unless current_user end end
Sessions rely on cookies, so users must have cookies enabled in their browser.
Always use secure cookies (HTTPS) in production to protect session data.
Do not store sensitive data directly in the session; store only user IDs or tokens.
Session-based authentication remembers users by storing their ID in a server-side session.
Use session[:user_id] to track logged-in users.
Clear the session to log users out safely.