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:
- Getting the API Keys for reCAPTCHA
- Set Up a Rails App
- Install Recaptcha Gem
- Configure Recaptcha in Your Application
- Implement Recaptcha in a Form
- Validate Recaptcha on the Server Side
- 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.
- Go to the Google reCAPTCHA Admin page.
- Click on the “+”, or the “Create” button to create a new site.
- Enter a label for your site (it can be anything descriptive).
- Choose reCAPTCHA v3.
- Enter your domain in the “Domains” section.
- Accept the reCAPTCHA Terms of Service and send alerts to owners.
- 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.