Ror Security
title: Ruby on Rails Security — Complete Guide to Securing Rails Apps description: 'Learn Ruby on Rails security: SQL injection prevention, XSS protection, CSRF tokens, mass assignment, session security, and Rails security defaults.' date: 2026-06-28 lastmod: 2026-06-28 weight: 31 tags: [backend, ror]
Rails includes built-in security features (CSRF tokens, parameter sanitization, SQL injection prevention) and follows security best practices to protect web applications from common vulnerabilities.
## What You'll Learn
By the end of this tutorial, you'll understand Rails' built-in security protections, prevent SQL injection with Active Record, protect against XSS, configure CSRF tokens, secure sessions, and handle mass assignment.
## Real-World Use
A Rails e-commerce site benefits from Rails' built-in CSRF protection (every form must have a valid token), parameter sanitization (strong parameters prevent mass assignment), and auto-escaped ERB output (prevents XSS).
## Security Learning Path
```mermaid
flowchart LR
A[Caching] --> B[Security]
B --> C[Docker]
C --> D[Deployment]
D --> E[Reference]
B --> F{You Are Here}
style F fill:#f90,color:#fff
SQL Injection Prevention
# BAD - vulnerable to SQL injection
User.where("name = '#{params[:name]}'")
# GOOD - Active Record sanitizes
User.where(name: params[:name])
# GOOD - with placeholders
User.where("name LIKE ?", "%#{params[:query]}%")
User.where("name LIKE :query", query: "%#{params[:query]}%")
# Using sanitize_sql for raw SQL
User.where(User.sanitize_sql(["name = ?", params[:name]]))
XSS Protection
<!-- BAD - vulnerable to XSS -->
<%= @post.body.html_safe %> <!-- Only use with trusted content -->
<!-- GOOD - Rails auto-escapes in ERB -->
<%= @post.body %> <!-- HTML is escaped automatically -->
<!-- SANITIZE - allow certain tags -->
<%= sanitize @post.body, tags: %w[b i em strong a],
attributes: %w[href] %>
<!-- STRIP TAGS - remove all HTML -->
<%= strip_tags @post.body %>
CSRF Protection
# ApplicationController (Rails default)
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
end
# In forms (form_with includes token automatically)
<%= form_with model: @post do |form| %>
<!-- CSRF token included in hidden field -->
<% end %>
# For AJAX requests (include token in meta tag)
<%= csrf_meta_tags %>
Session Security
# config/initializers/session_store.rb
Rails.application.config.session_store :cookie_store,
key: "_myapp_session",
secure: Rails.env.production?, # HTTPS only
httponly: true, # Not accessible by JavaScript
same_site: :lax, # CSRF protection
expire_after: 2.weeks # Session timeout
# Alternative: server-side sessions
Rails.application.config.session_store :redis_store,
servers: ENV.fetch("REDIS_URL", "redis://localhost:6379/0/session"),
expire_after: 2.weeks
Strong Parameters
class UsersController < ApplicationController
def create
@user = User.new(user_params) # Only permitted params
if @user.save
redirect_to @user
else
render :new
end
end
private
def user_params
params.require(:user).permit(:name, :email, :password)
# :role and :admin are NOT permitted (prevents privilege escalation)
end
end
Common Mistakes
1. Using html_safe Improperly
Calling html_safe on user-generated content opens XSS vulnerabilities. Use sanitize instead.
2. Removed protect_from_forgery
Disabling CSRF protection without understanding the implications leaves forms vulnerable to cross-site requests.
3. Weak Password Requirements
Devise's default password length is 6 characters. Require at least 8 characters with mixed case and numbers.
4. Not Using HTTPS in Production
Without HTTPS, all data (including session cookies) travels unencrypted. Force HTTPS in production.
5. Allowing Mass Assignment on Sensitive Attributes
Permitting :admin, :role_id, or :credit_card_number in strong parameters lets users set these values.
Practice Questions
1. How does Rails prevent SQL injection?
Active Record automatically sanitizes parameters in where(), create(), and update() calls. Use placeholders for raw SQL.
2. What is CSRF protection in Rails?
protect_from_forgery validates that POST/PUT/DELETE requests include a token that only the legitimate site can generate.
3. How do you prevent XSS in Rails views?
Rails auto-escapes output in ERB templates (<%= %>). For trusted HTML, use sanitize() to allow specific tags.
4. What are strong parameters?
params.require(:model).permit(:attrs) whitelists allowed parameters, preventing mass assignment of unintended attributes.
5. Challenge: Configure a secure Rails app with HTTPS, CSRF, and strong parameters.
# config/environments/production.rb
config.force_ssl = true
# ApplicationController
protect_from_forgery with: :exception
# Strong params
def user_params
params.require(:user).permit(:name, :email, :password)
end
FAQ
Mini Project: Secure Rails Setup
Configure a Rails app with HTTPS, CSRF, strong parameters, and content security policy.
# config/initializers/content_security_policy.rb
Rails.application.config.content_security_policy do |policy|
policy.default_src :self
policy.font_src :self, :https
policy.img_src :self, :https
policy.script_src :self, :https
policy.style_src :self, :https
end
What's Next
Ruby on Rails Docker Ruby on Rails Deployment
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro