0
0
Ruby on Railsframework~5 mins

CSRF protection in Ruby on Rails

Choose your learning style9 modes available
Introduction

CSRF protection stops bad websites from tricking you into doing things you don't want on other sites. It keeps your actions safe and private.

When you have forms that change data, like submitting a comment or updating a profile.
When your app accepts POST, PUT, PATCH, or DELETE requests from users.
When you want to make sure only your website can send important requests.
When you want to protect users from malicious attacks that use their login without permission.
Syntax
Ruby on Rails
class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
end
This line is usually in ApplicationController to protect all controllers by default.
The :exception option stops the request if the CSRF token is missing or wrong.
Examples
This option resets the session instead of raising an error, useful for APIs.
Ruby on Rails
class ApplicationController < ActionController::Base
  protect_from_forgery with: :null_session
end
Rails automatically adds a hidden CSRF token field in forms created with helpers like form_with.
Ruby on Rails
<%= form_with(model: @post) do |form| %>
  <%= form.text_field :title %>
  <%= form.submit %>
<% end %>
Use this to skip CSRF check for specific actions like webhooks that come from external services.
Ruby on Rails
skip_before_action :verify_authenticity_token, only: [:webhook]
Sample Program

This example shows a simple posts controller with CSRF protection enabled by default. The form automatically includes the CSRF token, so Rails can verify requests are safe.

Ruby on Rails
class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
end

class PostsController < ApplicationController
  def new
    @post = Post.new
  end

  def create
    @post = Post.new(post_params)
    if @post.save
      redirect_to @post
    else
      render :new
    end
  end

  private

  def post_params
    params.require(:post).permit(:title, :content)
  end
end

# In the view (new.html.erb):
# <%= form_with(model: @post) do |form| %>
#   <%= form.text_field :title %>
#   <%= form.text_area :content %>
#   <%= form.submit %>
# <% end %>
OutputSuccess
Important Notes

Always use Rails form helpers to get automatic CSRF tokens.

APIs often use :null_session or skip CSRF checks because they use other security methods.

CSRF tokens change with each session to keep protection strong.

Summary

CSRF protection stops unwanted actions from other sites.

Rails adds CSRF tokens automatically in forms created with helpers.

Use protect_from_forgery in ApplicationController to enable protection.