All Lessons / How Cross-Site Request Forgery (CSRF) Works in Ruby on Rails

Want more GoRails?

GoRails is packed full with over 350 lessons just like this one.

Sign up to get full access or log in to your account and sit back.

How Cross-Site Request Forgery (CSRF) Works in Ruby on Rails

#432 ยท February 8, 2022

Your Teacher

Hi, I'm Chris. I'm the creator of GoRails, and Jumpstart. I spend my time creating tutorials and tools to help Ruby on Rails developers build apps better and faster.

About This Episode

Ever gotten an InvalidAuthentictyToken error in Rails and wondered how CSRF works? In this lesson, we'll learn how it works behind the scenes so you can understand exactly what's going on.



Add this code to your ApplicationController to see how Rails compares the CSRF tokens you sent to the CSRF token in your application.

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception

  before_action do
    p "๐Ÿ‘‹"
    p "real #{real_csrf_token(session)}"
    p "global #{global_csrf_token(session)}"

    request_authenticity_tokens.each do |token|
      next if token.nil?

      decoded_token = decode_csrf_token(token)
      if decoded_token.length == AUTHENTICITY_TOKEN_LENGTH * 2
        p unmask_token(decoded_token)
        p decoded_token

Additional Reading:


logo Created with Sketch.

Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more. Icons by Icons8

© 2023 GoRails, LLC. All rights reserved.