百科.dev
全部条目AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
R

recaptcha

> 后端框架
开源

针对 Ruby 应用程序的 ReCaptcha 插件

2.0K stars0 点赞4 次浏览
访问官网GitHub

工具介绍

针对 Ruby 应用程序的 ReCaptcha 插件

reCAPTCHA

Author: Jason L Perry (http://ambethia.com)
Copyright: Copyright (c) 2007-2013 Jason L Perry
License: MIT
Info: https://github.com/ambethia/recaptcha
Bugs: https://github.com/ambethia/recaptcha/issues

This gem provides helper methods for the reCAPTCHA API. In your views you can use the recaptcha_tags method to embed the needed javascript, and you can validate in your controllers with verify_recaptcha or verify_recaptcha!, which raises an error on failure.

Table of Contents

  1. Obtaining a key
  2. Rails Installation
  3. Sinatra / Rack / Ruby Installation
  4. reCAPTCHA V2 API & Usage
  • recaptcha_tags
  • verify_recaptcha
  • invisible_recaptcha_tags
  1. reCAPTCHA V3 API & Usage
  • recaptcha_v3
  • verify_recaptcha (use with v3)
  • recaptcha_reply
  1. I18n Support
  2. Testing
  3. Alternative API Key Setup

Obtaining a key

Go to the reCAPTCHA admin console to obtain a reCAPTCHA API key.

The reCAPTCHA type(s) that you choose for your key will determine which methods to use below.

reCAPTCHA type Methods to use Description
v3 recaptcha_v3 Verify requests with a score
v2 Checkbox
("I'm not a robot" Checkbox)
recaptcha_tags Validate requests with the "I'm not a robot" checkbox
v2 Invisible
(Invisible reCAPTCHA badge)
invisible_recaptcha_tags Validate requests in the background

Note: You can only use methods that match your key's type. You cannot use v2 methods with a v3 key or use recaptcha_tags with a v2 Invisible key, for example. Otherwise you will get an error like "Invalid key type" or "This site key is not enabled for the invisible captcha."

Note: Enter localhost or 127.0.0.1 as the domain if using in development with localhost:3000.

Rails Installation

If you are having issues with Rails 7, Turbo, and Stimulus, make sure to check this Wiki page!

gem "recaptcha"

You can keep keys out of the code base with environment variables or with Rails secrets.

In development, you can use the dotenv gem. (Make sure to add it above gem 'recaptcha'.)

See Alternative API key setup for more ways to configure or override keys. See also the Configuration documentation.

export RECAPTCHA_SITE_KEY   = '6Lc6BAAAAAAAAChqRbQZcn_yyyyyyyyyyyyyyyyy'
export RECAPTCHA_SECRET_KEY = '6Lc6BAAAAAAAAKN3DRm6VA_xxxxxxxxxxxxxxxxx'

If you have an Enterprise API key:

export RECAPTCHA_ENTERPRISE            = 'true'
export RECAPTCHA_ENTERPRISE_API_KEY    = 'AIzvFyE3TU-g4K_Kozr9F1smEzZSGBVOfLKyupA'
export RECAPTCHA_ENTERPRISE_PROJECT_ID = 'my-project'

note: you'll still have to provide RECAPTCHA_SITE_KEY, which will hold the value of your enterprise recaptcha key id. You will not need to provide a RECAPTCHA_SECRET_KEY, however.

RECAPTCHA_ENTERPRISE_API_KEY is the enterprise key of your Google Cloud Project, which you can generate here: https://console.cloud.google.com/apis/credentials.

Add recaptcha_tags to the forms you want to protect:

<%= form_for @foo do |f| %>
  # …
  <%= recaptcha_tags %>
  # …
<% end %>

Then, add verify_recaptcha logic to each form action that you've protected:

# app/controllers/users_controller.rb
@user = User.new(params[:user].permit(:name))
if verify_recaptcha(model: @user) && @user.save
  redirect_to @user
else
  render 'new'
end

Please note that this setup uses reCAPTCHA_v2. For a recaptcha_v3 use, please refer to reCAPTCHA_v3 setup.

Sinatra / Rack / Ruby installation

See sinatra demo for details.

  • add gem 'recaptcha' to Gemfile
  • set env variables
  • include Recaptcha::Adapters::ViewMethods where you need recaptcha_tags
  • include Recaptcha::Adapters::ControllerMethods where you need verify_recaptcha

reCAPTCHA v2 API and Usage

recaptcha_tags

Use this when your key's reCAPTCHA type is "v2 Checkbox".

The following options are available:

Option Description
:theme Specify the theme to be used per the API. Available options: dark and light. (default: light)
:ajax Render the dynamic AJAX captcha per the API. (default: false)
:site_key Override site API key from configuration
:error Override the error code returned from the reCAPTCHA API (default: nil)
:size Specify a size (default: nil)
:nonce Optional. Sets nonce attribute for script. Can be generated via SecureRandom.base64(32). Use content_security_policy_nonce if you have config.content_security_policy_nonce_generator set in Rails. (default: nil)
:id Specify an html id attribute (default: nil)
:callback Optional. Name of success callback function, executed when the user submits a successful response
:expired_callback Optional. Name of expiration callback function, executed when the reCAPTCHA response expires and the user needs to re-verify.
:error_callback Optional. Name of error callback function, executed when reCAPTCHA encounters an error (e.g. network connectivity)
:noscript Include <noscript> content (default: true)

JavaScript resource (api.js) parameters:

Option Description
:onload Optional. The name of your callback function to be executed once all the dependencies have loaded. (See explicit rendering)
:render Optional. Whether to render the widget explicitly. Defaults to onload, which will render the widget in the first g-recaptcha tag it finds. (See explicit rendering)
:hl Optional. Forces the widget to render in a specific language. Auto-detects the user's language if unspecified. (See language codes)
:script Alias for :external_script. If you do not need to add a script tag by helper you can set the option to false. It's necessary when you add a script tag manualy (default: true).
:external_script Set to false to avoid including a script tag for the external api.js resource. Useful when including multiple recaptcha_tags on the same page.
:script_async Set to false to load the external api.js resource synchronously. (default: true)
:script_defer Set to true to defer loading of external api.js until HTML documen has been parsed. (default: true)

Any unrecognized options will be added as attributes on the generated tag.

You can also override the html attributes for the sizes of the generated textarea and iframe elements, if CSS isn't your thing. Inspect the source of recaptcha_tags to see these options.

Note that you cannot submit/verify the same response token more than once or you will get a timeout-or-duplicate error code. If you need reset the captcha and generate a new response token, then you need to call grecaptcha.reset().

verify_recaptcha

This method returns true or false after processing the response token from the reCAPTCHA widget. This is usually called from your controller, as seen above.

Passing in the ActiveRecord object via model: object is optional. If you pass a model—and the captcha fails to verify—an error will be added to the object for you to use (available as object.errors).

Why isn't this a model validation? Because that violates MVC. You can use it like this, or how ever you like.

Some of the options available:

Option Description
:model Model to set errors.
:attribute Model attribute to receive errors. (default: :base)
:message Custom error message.
:secret_key Override the secret API key from the configuration.
:enterprise_api_key Override the Enterprise API key from the configuration.
:enterprise_project_id Override the Enterprise project ID from the configuration.
:timeout The number of seconds to wait for reCAPTCHA servers before give up. (default: 3)
:response Custom response parameter. (default: params['g-recaptcha-response-data'])
:hostname Expected hostname or a callable that validates the hostname, see domain validation and hostname docs. (default: nil, but can be changed by setting config.hostname)
:env Current environment. The request to verify will be skipped if the environment is specified in configuration under skip_verify_env
:json Boolean; defaults to false; if true, will submit the verification request by POST with the request data in JSON

invisible_recaptcha_tags

Use this when your key's reCAPTCHA type is "v2 Invisible".

For more information, refer to: Invisible reCAPTCHA.

This is similar to recaptcha_tags, with the following additional options that are only available on invisible_recaptcha_tags:

Option Description
:ui The type of UI to render for this "invisible" widget. (default: :button)
:button: Renders a <button type="submit"> tag with options[:text] as the button text.
:invisible: Renders a <div> tag.
:input: Renders a <input type="submit"> tag with options[:text] as the button text.
:text The text to show for the button. (default: "Submit")
:inline_script If you do not need this helper to add an inline script tag, you can set the option to false (default: true).

It also accepts most of the options that recaptcha_tags accepts, including the following:

Option Description
:site_key Override site API key from configuration
:nonce Optional. Sets nonce attribute for script tag. Can be generated via SecureRandom.base64(32). Use content_security_policy_nonce if you have config.content_security_policy_nonce_generator set in Rails. (default: nil)
:id Specify an html id attribute (default: nil)

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

Rubycaptcharailsrecaptcharuby

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月17日
分类后端框架
定价开源

> 相关工具

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架