recaptcha Ruby Gem

repository·master·Indexed 24 days ago

https://github.com/ambethia/recaptcha

A Ruby library providing helper methods to integrate Google reCAPTCHA v2 (Checkbox and Invisible) and v3 into Rails, Sinatra, and Rack applications. It includes support for reCAPTCHA Enterprise, view helpers like recaptcha_tags and recaptcha_v3, and controller validation via verify_recaptcha.

Tokens
8.3K
Snippets
21
Records
49
Agent score
84%

What's inside recaptcha

  1. Use reCAPTCHA v3 for invisible verification

    master

    reCAPTCHA v3 is an invisible verification method that does not interrupt users. Unlike v2, it requires specifying an action in both the frontend and backend and allows you to define a minimum_score threshold to determine if a user is a human or a robot. If a score falls below your threshold, you can implement fallback logic such as requiring two-factor authentication or showing a v2 checkbox challenge.

    To implement a fallback pattern (v3 $\rightarrow$ v2):

    1. Use recaptcha_v3 in your view.
    2. In your controller, call verify_recaptcha with a minimum_score.
    3. If v3 fails, attempt verify_recaptcha without arguments (v2 mode) and show the recaptcha_tags in the view if necessary.
    # app/controllers/sessions_controller.rb
    def create
      success = verify_recaptcha(action: 'login', minimum_score: 0.5, secret_key: ENV['RECAPTCHA_SECRET_KEY_V3'])
      checkbox_success = verify_recaptcha unless success
      if success || checkbox_success
        # Perform action
      else
        if !success
          @show_checkbox_recaptcha = true
        end
        render 'new'
      end
    end
  2. Handle multiple reCAPTCHA actions on one page

    master

    You can execute reCAPTCHA multiple times with different actions on the same page. Each action must be verified individually in the controller.

    When multiple actions are submitted in a single request, the response tokens are passed as a hash under params['g-recaptcha-response-data'], using the action name as the key.

    Best Practice: Use external_script: false on all but one of the recaptcha_v3 calls to avoid including the external api.js script multiple times for the same site_key.

    # Controller verification
    result_a = verify_recaptcha(action: 'a')
    result_b = verify_recaptcha(action: 'b')
  3. Obtain reCAPTCHA API keys

    master

    To use this gem, you must first obtain API keys from the reCAPTCHA admin console. The specific methods you use in your application depend on the reCAPTCHA type you select:

    • v3: Use recaptcha_v3. This verifies requests using a score.
    • v2 Checkbox ("I'm not a robot"): Use recaptcha_tags. This validates requests via a checkbox.
    • v2 Invisible (Invisible badge): Use invisible_recaptcha_tags. This validates requests in the background.

    Important: You must use the method that matches your key type. Using a v2 method with a v3 key (or vice versa) will result in errors such as Invalid key type or This site key is not enabled for the invisible captcha.

    If developing locally on localhost:3000, ensure you add localhost or 127.0.0.1 as a permitted domain in the reCAPTCHA admin console.

  4. Configure reCAPTCHA keys and settings

    master

    Use Recaptcha.configure in a Rails initializer (e.g., config/initializers/recaptcha.rb) to set your global site_key and secret_key. You can also configure a proxy server, enable Enterprise API mode, and provide Enterprise-specific credentials.

    # config/initializers/recaptcha.rb
    Recaptcha.configure do |config|
      config.site_key  = '6Lc6BAAAAAAAAChqRbQZcn_yyyyyyyyyyyyyyyyy'
      config.secret_key = '6Lc6BAAAAAAAAKN3DRm6VA_xxxxxxxxxxxxxxxxx'
    
      # Uncomment the following line if you are using a proxy server:
      # config.proxy = 'http://myproxy.com.au:8080'
    
      # Uncomment the following lines if you are using the Enterprise API:
      # config.enterprise = true
      # config.enterprise_api_key = 'AIzvFyE3TU-g4K_Kozr9F1smEzZSGBVOfLKyupA'
      # config.enterprise_project_id = 'my-project'
    end
  5. Run reCAPTCHA v3 Rails examples

    master

    To run the v3 examples, you must obtain your own v3 keys from the Google reCAPTCHA Admin Console, as there are no standard testing keys for v3.

    Set the following environment variables before starting the server:

    1. export RECAPTCHA_SITE_KEY=your_v3_key
    2. export RECAPTCHA_SECRET_KEY=your_v3_key
    3. Start the server: rails s
    4. Visit: http://localhost:3000/v3_captchas
    export RECAPTCHA_SITE_KEY=your_v3_key
    export RECAPTCHA_SECRET_KEY=your_v3_key
    rails s
  6. Install recaptcha in Sinatra, Rack, or plain Ruby

    master

    To use the gem outside of Rails:

    1. Add gem 'recaptcha' to your Gemfile.
    2. Set the required environment variables (RECAPTCHA_SITE_KEY, etc.).
    3. Include the necessary adapter modules in your classes:
      • For view helpers (like recaptcha_tags): include Recaptcha::Adapters::ViewMethods
      • For controller validation (like verify_recaptcha): include Recaptcha::Adapters::ControllerMethods
  7. Enable reCAPTCHA in test environments

    master

    By default, reCAPTCHA is skipped in test and cucumber environments. To enable verification during testing, modify the skip_verify_env configuration.

    Recaptcha.configuration.skip_verify_env.delete("test")
  8. Configure hCaptcha support

    master

    Since hCaptcha provides a compatible reCAPTCHA API, you can use this gem with hCaptcha by setting the verify_url and api_server_url to hCaptcha endpoints. You must also increase the response_limit because hCaptcha responses can exceed the standard 4000-character reCAPTCHA limit.

    # config/initializers/recaptcha.rb
    Recaptcha.configure do |config|
      config.site_key  = '6Lc6BAAAAAAAAChqRbQZcn_yyyyyyyyyyyyyyyyy'
      config.secret_key = '6Lc6BAAAAAAAAKN3DRm6VA_xxxxxxxxxxxxxxxxx'
      config.verify_url = 'https://hcaptcha.com/siteverify'
      config.api_server_url = 'https://hcaptcha.com/1/api.js'
      config.response_limit = 100000
      config.response_minimum = 100
    end
  9. Run reCAPTCHA v3 with v2 fallback example

    master

    To run the specific example demonstrating v3 with a v2 fallback, you must unset the standard v2 keys and provide the v3 keys using specific environment variable suffixes (_V3).

    1. Unset existing keys:
      • unset RECAPTCHA_SITE_KEY
      • unset RECAPTCHA_SECRET_KEY
    2. Set v3 keys:
      • export RECAPTCHA_SITE_KEY_V3=your_v3_key
      • export RECAPTCHA_SECRET_KEY_V3=your_v3_key
    3. Start the server: rails s
    4. Visit: http://localhost:3000/v3_captchas?with_v2_fallback=1
    unset RECAPTCHA_SITE_KEY
    unset RECAPTCHA_SECRET_KEY
    export RECAPTCHA_SITE_KEY_V3=your_v3_key
    export RECAPTCHA_SECRET_KEY_V3=your_v3_key
    rails s
  10. Configure reCAPTCHA API keys via environment variables

    master

    You can manage your keys using environment variables. For local development, it is recommended to use the dotenv gem (ensure it is loaded before gem 'recaptcha' in your Gemfile).

    Standard reCAPTCHA keys

    export RECAPTCHA_SITE_KEY   = 'YOUR_SITE_KEY'
    export RECAPTCHA_SECRET_KEY = 'YOUR_SECRET_KEY'

    reCAPTCHA Enterprise keys

    If using Enterprise, provide the following. Note that RECAPTCHA_SITE_KEY should hold your enterprise reCAPTCHA key ID, and RECAPTCHA_SECRET_KEY is not required.

    export RECAPTCHA_ENTERPRISE            = 'true'
    export RECAPTCHA_ENTERPRISE_API_KEY    = 'YOUR_GOOGLE_CLOUD_PROJECT_CREDENTIAL'
    export RECAPTCHA_ENTERPRISE_PROJECT_ID = 'your-project-id'
    export RECAPTCHA_SITE_KEY   = '6Lc6BAAAAAAAAChqRbQZcn_yyyyyyyyyyyyyyyyy'
    export RECAPTCHA_SECRET_KEY = '6Lc6BAAAAAAAAKN3DRm6VA_xxxxxxxxxxxxxxxxx'