Skip to content
Menu
Railshero
  • Blog
  • About Me
  • Contact Me
  • Privacy Policy
Railshero
rercaptcha

Implementing reCAPTCHA in a Rails App

Posted on June 26, 2023June 30, 2023 by Rails Hero

As Web developers, we’re acutely aware of the need to arm our digital domains against the relentless siege of bots and spam. Among the arsenal at our disposal, CAPTCHA (the acronym for Completely Automated Public Turing test to tell Computers and Humans Apart) stands as a formidable sentinel. Google’s reCAPTCHA, especially, has gained a wide adoption due to its efficacy.

Here, I’ll delve into the intricacies of weaving Google’s reCAPTCHA v3 into the fabric of a Rails application, making it a seamless part of the user experience.

Here’s a list of what we’ll be doing:

  1. Getting the API Keys for reCAPTCHA
  2. Set Up a Rails App
  3. Install Recaptcha Gem
  4. Configure Recaptcha in Your Application
  5. Implement Recaptcha in a Form
  6. Validate Recaptcha on the Server Side
  7. Handling the Recaptcha Score

Before beginning, make sure that you have the following:

  • A Ruby on Rails application that’s ready for action
  • A foundational understanding of Rails application mechanics
  • A Google account (your key to the reCAPTCHA universe)

Let’s dive in!

Step 1: Get API Keys for reCAPTCHA

To start using Google reCAPTCHA in your Rails application, you first need to acquire site keys from the Google reCAPTCHA Admin console.

  1. Go to the Google reCAPTCHA Admin page.
  2. Click on the “+”, or the “Create” button to create a new site.
  3. Enter a label for your site (it can be anything descriptive).
  4. Choose reCAPTCHA v3.
  5. Enter your domain in the “Domains” section.
  6. Accept the reCAPTCHA Terms of Service and send alerts to owners.
  7. Click on “Submit”.

You’ll be presented with a SITE KEY and a SECRET KEY. The Site Key is what we’ll use in the frontend of our Rails app, while the Secret Key is used in the backend for validation.

Do not share your Secret Key with anyone or publish it online as it is important for your site’s security.

Step 2: Set Up a Rails App

Let’s assume you have a Ruby on Rails application running. If not, you can quickly set one up by following this guide.

Step 3: Install Recaptcha Gem

The recaptcha gem, developed by Ambethia, provides a simple way to implement reCAPTCHA in Rails. To add it to your project, include it in your Gemfile:

gem 'recaptcha', require: 'recaptcha/rails'

Then, run bundler to install the gem in your project:

bundle install

Step 4: Configure Recaptcha in Your Application

After installing the recaptcha gem, you need to configure it in your Rails application using the SITE KEY and SECRET KEY you got from Google.

Create a config/initializers/recaptcha.rb file in your Rails application. In this file, add the following:

Recaptcha.configure do |config|
config.site_key = 'your-site-key'
config.secret_key = 'your-secret-key'
# Uncomment the following line if you are using a proxy server:
# config.proxy = 'http://myproxy.com.au:8080'
end

Make sure to replace 'your-site-key' and 'your-secret-key' with your actual keys.

To avoid revealing your keys in the code (especially if it’s publicly accessible), it’s better to use environment variables. Rails uses the dotenv gem for this. Create a .env file in your Rails root directory, and add the following:

RECAPTCHA_SITE_KEY=your-site-key
RECAPTCHA_SECRET_KEY=your-secret-key

Then, your config/initializers/recaptcha.rb would look like this:

Recaptcha.configure do |config|
config.site_key = ENV['RECAPTCHA_SITE_KEY']
config.secret_key = ENV['RECAPTCHA_SECRET_KEY']
# Uncomment the following line if you are using a proxy server:
# config.proxy = 'http://myproxy.com.au:8080'
end

Don’t forget to add .env to your .gitignore file so it’s not tracked in your version control system.

Step 5: Implement Recaptcha in a Form

Next, you’ll implement reCAPTCHA in one of your forms. As an example, we’ll add it to a sign-up form.

First, you need to include the reCAPTCHA script on your page. You can do this by adding the following line to your app/views/layouts/application.html.erb in the head section:

<%= recaptcha_v3_script_tag %>

Next, add the following line to your sign-up form, found in app/views/devise/registrations/new.html.erb:

<%= recaptcha_v3(action: 'signup', callback: 'callbackFunction') %>

The action attribute helps you identify this specific captcha in your reCAPTCHA admin console. The callback is a function that will be called when the user submits the form.

In your JavaScript file (app/assets/javascripts/application.js), create the callbackFunction:

function callbackFunction(token) {
const element = document.getElementById('g-recaptcha-response');
if (element) {
element.value = token;
}
}

Step 6: Validate Recaptcha on the Server Side

Now that you’ve set up reCAPTCHA in the form, you need to validate it on the server side when the form is submitted.

In your registrations controller (app/controllers/users/registrations_controller.rb), you can use the verify_recaptcha method provided by the recaptcha gem to validate the token.

class Users::RegistrationsController < Devise::RegistrationsController
def create
if verify_recaptcha(action: 'signup') && @user.save
super
else
build_resource(sign_up_params)
clean_up_passwords(resource)
flash.now[:alert] = "reCAPTCHA verification failed, please try again."
render :new
end
end
end

The verify_recaptcha method sends a request to the reCAPTCHA API and validates the user’s response. If the response passes the check and the user’s data is saved successfully, the signup process continues. Otherwise, the user is redirected back to the signup form with an alert message.

Step 7: Handling the Recaptcha Score

A unique feature of Google’s reCAPTCHA v3 is its score system (1.0 suggests a likely genuine interaction, while 0.0 hints at a probable bot). You can use this score to decide whether to permit the action, request the user to validate themselves again, or outrightly block the action.

To handle the reCAPTCHA score in your Rails application, you can modify your verify_recaptcha call in the create action:

class Users::RegistrationsController < Devise::RegistrationsController
def create
recaptcha_result = verify_recaptcha(action: 'signup', minimum_score: 0.5)
if recaptcha_result['score'] && @user.save
super
else
build_resource(sign_up_params)
clean_up_passwords(resource)
flash.now[:alert] = "reCAPTCHA verification failed, please try again."
render :new
end
end
end

In the code above, the minimum_score option allows you to specify the minimum score that you consider acceptable for your site.


And voila! You’ve constructed a sturdy fortress, protecting your Ruby on Rails application from spam and bot attacks using Google’s reCAPTCHA v3. Remember to fine-tune the reCAPTCHA score threshold to your application’s requirements and keep a watchful eye on the reCAPTCHA admin console to ensure the best protection.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Tags

active record active storage assets assign to many associations attachment attachments authentication authorization avatar bootstrap cdn config database deploy deployments devise DRY environment variables file uploads Gemfile gems has_many helpers heroku index indexing initializer javascript pagination parameters postgres production public routes.rb ruby gem ruby gems search sendgrid server smtp stylesheets variants views voting

Recent Posts

  • Understanding the DRY Principle in Rails
  • Building Multi-tenant Applications with Rails
  • Rails Basics: Templating Engines
  • Deploying With Capistrano
  • Automated Testing in Rails

Archives

  • July 2023
  • June 2023
  • October 2021
  • September 2021
  • August 2021
  • July 2021

Categories

  • Active Record
  • Activity Logging
  • Apps
  • Assets
  • Attachments
  • Audio
  • Authentication
  • Authorization
  • Deployments
  • Error Pages
  • File Uploads
  • General
  • Heroku
  • Heroku
  • Pagination
  • Rails Basics
  • RubyGems
  • Search Engine Optimization
  • Search/Indexing
  • Testing
  • User Interface
  • Video
  • Views & Templating
  • Voting
  • Web Security
©2025 Railshero | Theme: Wordly by SuperbThemes
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept All”, you consent to the use of ALL the cookies. However, you may visit "Cookie Settings" to provide a controlled consent.
Cookie SettingsAccept All
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.
Non-necessary
Any cookies that may not be particularly necessary for the website to function and is used specifically to collect user personal data via analytics, ads, other embedded contents are termed as non-necessary cookies. It is mandatory to procure user consent prior to running these cookies on your website.
SAVE & ACCEPT