`

# What is CSRF token?

228

A CSRF (Cross-Site Request Forgery) token in Rails is a security feature designed to protect your application from CSRF attacks. These attacks occur when a malicious website tricks a user’s browser into making unwanted requests to another site where the user is authenticated.

How CSRF Tokens Work
  1. Token Generation: When a user visits your Rails application, a unique CSRF token is generated and stored in the user’s session.
  2. Token Inclusion: This token is included in all forms and AJAX requests as a hidden field or request header.
  3. Token Verification: When the server receives a request, it checks the token against the one stored in the session. If they match, the request is allowed; otherwise, it is rejected.
Example

Here’s how you might see CSRF tokens in a Rails form:

<%= form_with(url: '/posts', method: 'post') do |form| %>
  <%= form.text_field :title %>
  <%= form.submit %>
<% end %>
Rails automatically includes the CSRF token in the form, ensuring that the request is secure.

Benefits of CSRF Tokens
  • Prevents Unauthorized Actions: Ensures that actions are performed by authenticated users and not by malicious scripts.
  • Enhances Security: Protects against a common web vulnerability, making your application more secure.
How Rails Implements CSRF Protection

Rails includes CSRF protection by default. The protect_from_forgery method is used in controllers to enable this protection:

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
end
This method ensures that all non-GET requests include a valid CSRF token.