How CSRF Tokens work in Ruby on Rails?

Category: Ruby :: Published at: 16.12.2024

All modern frameworks offer protection against CSRF attacks, so these attacks are not as common anymore.
However, this does not mean we don't need to understand what they are and how to protect ourselves from them.

In this article, I will explain what a Rails engineer needs to know about CSRF.

CSRF stands for Cross-Site Request Forgery. It is a type of attack that tricks a user into unintentionally generating a malicious request.

A typical CSRF attack on an unprotected VOD website:

  • Tom logs in to his VOD account
  • He does not log out, so his browser session remains active
  • A hacker steals Tom's session data
  • The hacker sends an email to Tom with a link to a malicious page
  • The link redirects to a legitimate VOD website endpoint designed to delete Tom's account
  • When Tom clicks the link, his account is deleted

If the VOD website were protected against CSRF attacks, this would not happen. Why?
Because the website would generate a special token upon page load or refresh and reject any requests that do not include this token.

This is precisely how Rails protects against CSRF attacks by default.

If you're using form_with, simple_form or any form generator, you will see that Rails will create a authenticity_token hidden input.

If you use turbo, you probably also have this code implemented:

<%= csrf_meta_tags %>

It will also create a generate a token that will protect you from CSRF attacks.

How to disable CSRF protection?

Sometimes, for example, when you are using API, and your session is on the client side, you don't need CSRF protection.

There is an easy way to disable it. You can just use this line in your application.rb

config.action_controller.allow_forgery_protection = false

 

 


- Click if you liked this article

Views: 323