How To: Use Recaptcha with Devise

Matt Yanchek edited this page Mar 28, 2018 · 50 revisions

To add Google's ReCaptcha to your site:

Install ReCaptcha gem

Please see ReCaptcha gem for installation details and API key setup.

Some of the available options for #verify_recaptcha can be found here.

Add ReCaptcha to views

Add <%= recaptcha_tags %> to the forms you want to protect and show recaptcha error.

Example for a page app/views/devise/registrations/new.html.erb

<%= flash[:recaptcha_error] %>
<%= recaptcha_tags %>

For details on how to edit devise views see configuring-views.

Add ReCaptcha verification in controllers

Include a prepend_before_action for any action you want to secure:

Devise::RegistrationsController

To add ReCaptcha in registration page, create a 'app/controllers/registrations_controller.rb`

class RegistrationsController < Devise::RegistrationsController
  prepend_before_action :check_captcha, only: [:create] # Change this to be any actions you want to protect.

  private
    def check_captcha
      unless verify_recaptcha
        self.resource = resource_class.new sign_up_params
        resource.validate # Look for any other validation errors besides Recaptcha
        set_minimum_password_length
        respond_with resource
      end 
    end
end

and configure devise for using your controller changing config/routes.rb

devise_for :users, controllers: { ... , registrations: "registrations", ... }

Devise::PasswordsController

To add ReCaptcha in password reset page, , create a app/controllers/passwords_controller.rb

class PasswordsController < Devise::PasswordsController
  prepend_before_action :check_captcha, only: [:create]

  private

  def check_captcha
    unless verify_recaptcha
      self.resource = resource_class.new
      resource.validate # Look for any other validation errors besides Recaptcha
      respond_with_navigational(resource) { render :new }
    end
  end
end

and configure devise for using your controller changing config/routes.rb

devise_for :users, controllers: { ... , passwords: "passwords", ... }

Notes

Follow these instructions also if you are using devise generated controller (rails g devise:controller [scope]). In this case the route to use in devise_for is registrations: "user/registrations" and passwords: "user/passwords"

Clone this wiki locally
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.