0
0
Ruby on Railsframework~30 mins

CSRF protection in Ruby on Rails - Mini Project: Build & Apply

Choose your learning style9 modes available
CSRF Protection in Rails
📖 Scenario: You are building a simple Rails web application that allows users to submit a contact form. To keep your app safe from malicious attacks, you need to add protection against Cross-Site Request Forgery (CSRF).
🎯 Goal: Learn how to enable and verify CSRF protection in a Rails controller and form, so your app only accepts form submissions from trusted sources.
📋 What You'll Learn
Create a Rails controller named ContactsController with a new and create action
Add CSRF protection by enabling protect_from_forgery in the controller
Create a simple HTML form in the new.html.erb view that includes the CSRF token
Verify that the create action only accepts requests with a valid CSRF token
💡 Why This Matters
🌍 Real World
CSRF protection is essential for any web app that accepts form submissions to prevent attackers from tricking users into submitting unwanted requests.
💼 Career
Understanding and implementing CSRF protection is a key skill for Rails developers to build secure web applications.
Progress0 / 4 steps
1
Create ContactsController with new and create actions
Create a Rails controller named ContactsController with two empty actions: new and create.
Ruby on Rails
Need a hint?

Use def new and def create inside the controller class.

2
Enable CSRF protection in ContactsController
Add the line protect_from_forgery with: :exception inside the ContactsController class to enable CSRF protection.
Ruby on Rails
Need a hint?

Place protect_from_forgery with: :exception inside the controller class but outside any method.

3
Create a form with CSRF token in new.html.erb
In the new.html.erb view file, create a form using form_with helper for the create action. Make sure the form includes the CSRF token automatically.
Ruby on Rails
Need a hint?

Use form_with with url: contacts_path and method: :post. Rails adds the CSRF token automatically.

4
Verify CSRF token in create action
In the create action of ContactsController, add code to safely handle the form submission. The CSRF token will be verified automatically by Rails because of protect_from_forgery. Add a simple redirect to new after submission.
Ruby on Rails
Need a hint?

You don't need to manually check the CSRF token. Just redirect after handling the form.