Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

ReCaptcha helpers for ruby apps

License

NotificationsYou must be signed in to change notification settings

ambethia/recaptcha

Repository files navigation

Gem Version

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 thereCAPTCHA API. In yourviews you can use therecaptcha_tags method to embed the needed javascript, and you can validatein your controllers withverify_recaptcha orverify_recaptcha!, which raises an error onfailure.

Table of Contents

  1. Obtaining a key
  2. Rails Installation
  3. Sinatra / Rack / Ruby Installation
  4. reCAPTCHA V2 API & Usage
  1. reCAPTCHA V3 API & Usage
  1. I18n Support
  2. Testing
  3. Alternative API Key Setup

Obtaining a key

Go to thereCAPTCHA 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 typeMethods to useDescription
v3recaptcha_v3Verify requests with ascore
v2 Checkbox
("I'm not a robot" Checkbox)
recaptcha_tagsValidate requests with the "I'm not a robot" checkbox
v2 Invisible
(Invisible reCAPTCHA badge)
invisible_recaptcha_tagsValidate requests in the background

Note: You canonly use methods that match your key's type. You cannot use v2 methods with a v3key or userecaptcha_tags with a v2 Invisible key, for example. Otherwise you will get anerror like "Invalid key type" or "This site key is not enabled for the invisible captcha."

Note: Enterlocalhost or127.0.0.1 as the domain if using in development withlocalhost:3000.

Rails Installation

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

gem"recaptcha"

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

In development, you can use thedotenv gem. (Make sure to add it abovegem 'recaptcha'.)

SeeAlternative API key setup for more ways to configure or overridekeys. See also theConfigurationdocumentation.

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 provideRECAPTCHA_SITE_KEY, which will hold the value of your enterprise recaptcha key id. You will not need to provide aRECAPTCHA_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.

Addrecaptcha_tags to the forms you want to protect:

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

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

# app/controllers/users_controller.rb@user=User.new(params[:user].permit(:name))ifverify_recaptcha(model:@user) &&@user.saveredirect_to@userelserender'new'end

Please note that this setup usesreCAPTCHA_v2. For arecaptcha_v3 use, please refer toreCAPTCHA_v3 setup.

Sinatra / Rack / Ruby installation

Seesinatra demo for details.

  • addgem 'recaptcha' toGemfile
  • set env variables
  • include Recaptcha::Adapters::ViewMethods where you needrecaptcha_tags
  • include Recaptcha::Adapters::ControllerMethods where you needverify_recaptcha

reCAPTCHA v2 API and Usage

recaptcha_tags

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

The following options are available:

OptionDescription
:themeSpecify the theme to be used per the API. Available options:dark andlight. (default:light)
:ajaxRender the dynamic AJAX captcha per the API. (default:false)
:site_keyOverride site API key from configuration
:errorOverride the error code returned from the reCAPTCHA API (default:nil)
:sizeSpecify a size (default:nil)
:nonceOptional. Sets nonce attribute for script. Can be generated viaSecureRandom.base64(32). Usecontent_security_policy_nonce if you haveconfig.content_security_policy_nonce_generator set in Rails. (default:nil)
:idSpecify an html id attribute (default:nil)
:callbackOptional. Name of success callback function, executed when the user submits a successful response
:expired_callbackOptional. Name of expiration callback function, executed when the reCAPTCHA response expires and the user needs to re-verify.
:error_callbackOptional. Name of error callback function, executed when reCAPTCHA encounters an error (e.g. network connectivity)
:noscriptInclude<noscript> content (default:true)

JavaScript resource (api.js) parameters:

OptionDescription
:onloadOptional. The name of your callback function to be executed once all the dependencies have loaded. (Seeexplicit rendering)
:renderOptional. Whether to render the widget explicitly. Defaults toonload, which will render the widget in the first g-recaptcha tag it finds. (Seeexplicit rendering)
:hlOptional. Forces the widget to render in a specific language. Auto-detects the user's language if unspecified. (Seelanguage codes)
:scriptAlias for:external_script. If you do not need to add a script tag by helper you can set the option tofalse. It's necessary when you add a script tag manualy (default:true).
:external_scriptSet tofalse to avoid including a script tag for the externalapi.js resource. Useful when including multiplerecaptcha_tags on the same page.
:script_asyncSet tofalse to load the externalapi.js resource synchronously. (default:true)
:script_deferSet totrue to defer loading of externalapi.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 generatedtextarea andiframeelements, if CSS isn't your thing. Inspect thesource ofrecaptcha_tagsto see these options.

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

verify_recaptcha

This method returnstrue orfalse after processing the response token from the reCAPTCHA widget.This is usually called from your controller, as seenabove.

Passing in the ActiveRecord object viamodel: object is optional. If you pass amodel—and thecaptcha fails to verify—an error will be added to the object for you to use (available asobject.errors).

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

Some of the options available:

OptionDescription
:modelModel to set errors.
:attributeModel attribute to receive errors. (default::base)
:messageCustom error message.
:secret_keyOverride the secret API key from the configuration.
:enterprise_api_keyOverride the Enterprise API key from the configuration.
:enterprise_project_idOverride the Enterprise project ID from the configuration.
:timeoutThe number of seconds to wait for reCAPTCHA servers before give up. (default:3)
:responseCustom response parameter. (default:params['g-recaptcha-response-data'])
:hostnameExpected hostname or a callable that validates the hostname, seedomain validation andhostname docs. (default:nil, but can be changed by settingconfig.hostname)
:envCurrent environment. The request to verify will be skipped if the environment is specified in configuration underskip_verify_env
:jsonBoolean; 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 torecaptcha_tags, with the following additional options that are only availableoninvisible_recaptcha_tags:

OptionDescription
:uiThe type of UI to render for this "invisible" widget. (default::button)
:button: Renders a<button type="submit"> tag withoptions[:text] as the button text.
:invisible: Renders a<div> tag.
:input: Renders a<input type="submit"> tag withoptions[:text] as the button text.
:textThe text to show for the button. (default:"Submit")
:inline_scriptIf you do not need this helper to add an inline script tag, you can set the option tofalse (default:true).

It also accepts most of the options thatrecaptcha_tags accepts, including the following:

OptionDescription
:site_keyOverride site API key from configuration
:nonceOptional. Sets nonce attribute for script tag. Can be generated viaSecureRandom.base64(32). Usecontent_security_policy_nonce if you haveconfig.content_security_policy_nonce_generator set in Rails. (default:nil)
:idSpecify an html id attribute (default:nil)
:scriptSame as setting both:inline_script and:external_script. If you only need one or the other, use:inline_script and:external_script instead.
:callbackOptional. Name of success callback function, executed when the user submits a successful response
:expired_callbackOptional. Name of expiration callback function, executed when the reCAPTCHA response expires and the user needs to re-verify.
:error_callbackOptional. Name of error callback function, executed when reCAPTCHA encounters an error (e.g. network connectivity)

JavaScript resource (api.js) parameters:

OptionDescription
:onloadOptional. The name of your callback function to be executed once all the dependencies have loaded. (Seeexplicit rendering)
:renderOptional. Whether to render the widget explicitly. Defaults toonload, which will render the widget in the first g-recaptcha tag it finds. (Seeexplicit rendering)
:hlOptional. Forces the widget to render in a specific language. Auto-detects the user's language if unspecified. (Seelanguage codes)
:external_scriptSet tofalse to avoid including a script tag for the externalapi.js resource. Useful when including multiplerecaptcha_tags on the same page.
:script_asyncSet tofalse to load the externalapi.js resource synchronously. (default:true)
:script_deferSet tofalse to defer loading of externalapi.js until HTML documen has been parsed. (default:true)

With a single form on a page

  1. Theinvisible_recaptcha_tags generates a submit button for you.
<%= form_for @foo do |f|%>  # ... other tags<%= invisible_recaptcha_tags text: 'Submit form'%><% end%>

Then, addverify_recaptcha to your controller as seenabove.

With multiple forms on a page

  1. You will need a custom callback function, which is called after verification with Google's reCAPTCHA service. This callback function must submit the form. Optionally,invisible_recaptcha_tags currently implements a JS function calledinvisibleRecaptchaSubmit that is called when nocallback is passed. Should you wish to overrideinvisibleRecaptchaSubmit, you will need to useinvisible_recaptcha_tags script: false, see lib/recaptcha/client_helper.rb for details.
  2. Theinvisible_recaptcha_tags generates a submit button for you.
<%= form_for @foo, html: {id: 'invisible-recaptcha-form'} do |f|%>  # ... other tags<%= invisible_recaptcha_tags callback: 'submitInvisibleRecaptchaForm', text: 'Submit form'%><% end%>
// app/assets/javascripts/application.jsvarsubmitInvisibleRecaptchaForm=function(){document.getElementById("invisible-recaptcha-form").submit();};

Finally, addverify_recaptcha to your controller as seenabove.

Programmatically invoke

  1. Specifyui option
<%= form_for @foo, html: {id: 'invisible-recaptcha-form'} do |f|%>  # ... other tags<buttontype="button"id="submit-btn">    Submit</button><%=invisible_recaptcha_tagsui::invisible,callback:'submitInvisibleRecaptchaForm'%><%end%>
// app/assets/javascripts/application.jsdocument.getElementById('submit-btn').addEventListener('click',function(e){// do some validationif(isValid){// call reCAPTCHA checkgrecaptcha.execute();}});varsubmitInvisibleRecaptchaForm=function(){document.getElementById("invisible-recaptcha-form").submit();};

reCAPTCHA v3 API and Usage

The main differences from v2 are:

  1. you must specify anaction in both frontend and backend
  2. you can choose the minimum score required for you to consider the verification a success(consider the user a human and not a robot)
  3. reCAPTCHA v3 is invisible (except for the reCAPTCHA badge) and will never interrupt your users;you have to choose which scores are considered an acceptable risk, and choose what to do (requiretwo-factor authentication, show a v3 challenge, etc.) if the score falls below the threshold youchoose

For more information, refer to thev3 documentation.

Examples

With v3, you can let all users log in without any intervention at all if their score is above somethreshold, and only show a v2 checkbox recaptcha challenge (fall back to v2) if it is below thethreshold:

This example sets v2 keys through environment variables. For more information on how to set up keys, please refer to thedocumentation here.

# .envRECAPTCHA_SITE_KEY=6Lc6BAAAAAAAAChqRbQZcn_yyyyyyyyyyyyyyyyyRECAPTCHA_SECRET_KEY=6Lc6BAAAAAAAAKN3DRm6VA_xxxxxxxxxxxxxxxxx
<% if @show_checkbox_recaptcha%><%= recaptcha_tags%><% else%><%= recaptcha_v3(action: 'login', site_key: ENV['RECAPTCHA_SITE_KEY_V3'])%><% end%>
# app/controllers/sessions_controller.rbdefcreatesuccess=verify_recaptcha(action:'login',minimum_score:0.5,secret_key:ENV['RECAPTCHA_SECRET_KEY_V3'])checkbox_success=verify_recaptchaunlesssuccessifsuccess ||checkbox_success# Perform actionelseif !success@show_checkbox_recaptcha=trueendrender'new'endend

(You can also find thisexample in the demo app.)

Another example:

<%= form_for @user do |f|%><%= recaptcha_v3(action: 'registration')%><% end%>
# app/controllers/users_controller.rbdefcreate@user=User.new(params[:user].permit(:name))recaptcha_valid=verify_recaptcha(model:@user,action:'registration')ifrecaptcha_validif@user.saveredirect_to@userelserender'new'endelse# Score is below threshold, so user may be a bot. Show a challenge, require multi-factor# authentication, or do something else.render'new'endend

recaptcha_v3

Adds an inline script tag that callsgrecaptcha.execute for the givensite_key andaction andcalls thecallback with the resulting response token. You need to verify this token withverify_recaptcha in your controller in order to get thescore.

By default, this inserts a hidden<input type="hidden"> tag. Thevalue of this input will automatically be set to the response token (by the default callbackfunction). This lets you includerecaptcha_v3 within a<form> tag and have it automaticallysubmit the token as part of the form submission.

Note: reCAPTCHA actually already adds its own hidden tag, like<textarea name="g-recaptcha-response-data">,immediately ater the reCAPTCHA badge in the bottom right of the page — but since it is not inside ofany<form> element, and since it already passes the token to the callback, this hiddentextareaisn't helpful to us.

If you need to submit the response token to the server in a different way than via a regular formsubmit, such as viaAjax orfetch,then you can either:

  1. just extract the token out of the hidden<input> or<textarea> (both of which will have apredictable name/id), likedocument.getElementById('g-recaptcha-response-data-my-action').value, or
  2. write and specify a customcallback function. You may also want to passelement: false if youdon't have a use for the hidden input element.

Note that you cannot submit/verify the same response token more than once or youwill get atimeout-or-duplicate error code. If you need reset the captcha andgenerate a new response token, then you need to callgrecaptcha.execute(…) orgrecaptcha.enterprise.execute(…) again. This helper provides a JavaScriptmethod (for each action) namedexecuteRecaptchaFor{action} to make thiseasier. That is the same method that is invoked immediately. It simply callsgrecaptcha.execute orgrecaptcha.enterprise.execute again and then calls thecallback function with the response token.

You will also get atimeout-or-duplicate error if too much time has passed between getting theresponse token and verifying it. This can easily happen with large forms that take the user a coupleminutes to complete. Unlike v2, where you can use theexpired-callback to be notified when theresponse expires, v3 appears to provide no such callback. See also1 and2.

To deal with this, it is recommended to call the "execute" in your form's submit handler (orimmediately before sending to the server to verify if not using a form) rather than using theresponse token that gets generated when the page first loads. TheexecuteRecaptchaFor{action}function mentioned above can be used if you want it to invoke a callback, or theexecuteRecaptchaFor{action}Async variant if you want aPromise that you canawait. Seedemo/rails/app/views/v3_captchas/index.html.erbfor an example of this.

This helper is similar to therecaptcha_tags/invisible_recaptcha_tags helpersbut only accepts the following options:

OptionDescription
:site_keyOverride site API key
:actionThe name of thereCAPTCHA action. Actions are not case-sensitive and may only contain alphanumeric characters, slashes, and underscores, and must not be user-specific.
:nonceOptional. Sets nonce attribute for script. Can be generated viaSecureRandom.base64(32). Usecontent_security_policy_nonce if you haveconfig.content_security_policy_nonce_generator set in Rails. (default:nil)
:callbackName of callback function to call with the token. Whenelement is:input, this defaults to a function namedsetInputWithRecaptchaResponseTokenFor#{sanitize_action(action)} that sets the value of the hidden input to the token.
:idSpecify a uniqueid attribute for the<input> element if usingelement: :input. (default:"g-recaptcha-response-data-" +action)
:nameSpecify a uniquename attribute for the<input> element if usingelement: :input. (default:g-recaptcha-response-data[action])
:scriptSame as setting both:inline_script and:external_script. (default:true).
:inline_scriptIftrue, adds an inline script tag that callsgrecaptcha.execute for the givensite_key andaction and calls thecallback with the resulting response token. Passfalse if you want to handle callinggrecaptcha.execute yourself. (default:true)
:elementThe element to render, if any (default::input)
:input: Renders a hidden<input type="hidden"> tag. The value of this will be set to the response token by the defaultsetInputWithRecaptchaResponseTokenFor{action} callback.
false: Doesn't render any tag. You'll have to add a custom callback that does something with the token.
:turboIftrue, calls the js function which executes reCAPTCHA after all the dependencies have been loaded. This cannot be used with the js param:onload. This makes reCAPTCHAv3 usable with turbo.
:turbolinksAlias of:turbo. Will be deprecated soon.
:ignore_no_elementIftrue, adds null element checker for forms that can be removed from the page by javascript like modals with forms. (default: true)

JavaScript resource (api.js) parameters:

OptionDescription
:onloadOptional. The name of your callback function to be executed once all the dependencies have loaded. (Seeexplicit rendering)
:external_scriptSet tofalse to avoid including a script tag for the externalapi.js resource. Useful when including multiplerecaptcha_tags on the same page.
:script_asyncSet totrue to load the externalapi.js resource asynchronously. (default:false)
:script_deferSet totrue to defer loading of externalapi.js until HTML documen has been parsed. (default:false)

If usingelement: :input, any unrecognized options will be added as attributes on the generated<input> element.

verify_recaptcha (use with v3)

This works the same as for v2, except that you may pass anaction andminimum_score if you wishto validate that the action matches or that the score is above the given threshold, respectively.

result=verify_recaptcha(action:'action/name')
OptionDescription
:actionThe name of thereCAPTCHA action that we are verifying. Set tofalse ornil to skip verifying that the action matches.
:minimum_scoreProvide a threshold to meet or exceed. Threshold should be a float between 0 and 1 which will be tested asscore >= minimum_score. (Default:nil)

Multiple actions on the same page

According tohttps://developers.google.com/recaptcha/docs/v3#placement,

Note: You can execute reCAPTCHA as many times as you'd like with different actions on the same page.

You will need to verify each action individually with a separate call toverify_recaptcha.

result_a=verify_recaptcha(action:'a')result_b=verify_recaptcha(action:'b')

Because the response tokens for multiple actions may be submitted together in the same request, theyare passed as a hash underparams['g-recaptcha-response-data'] with the action as the key.

It is recommended to passexternal_script: false on all but one of the calls torecaptcha since you only need to include the script tag once for a givensite_key.

recaptcha_reply andrecaptcha_failure_reason

Afterverify_recaptcha has been called, you can callrecaptcha_reply to get the raw reply from recaptcha. This can allow you to get the exact score returned by recaptcha should you need it.

ifverify_recaptcha(action:'login')redirect_to@userelsescore=recaptcha_reply['score']Rails.logger.warn("User#{@user.id} was denied login because of a recaptcha score of#{score}")render'new'end

recaptcha_reply will returnnil if the the reply was not yet fetched.

recaptcha_failure_reason will return information if verification failed. E.g. if params was wrong or api resulted some error-codes.

I18n support

reCAPTCHA supports the I18n gem (it comes with English translations)To override or add new languages, add toconfig/locales/*.yml

# config/locales/en.ymlen:recaptcha:errors:verification_failed:'reCAPTCHA was incorrect, please try again.'recaptcha_unreachable:'reCAPTCHA verification server error, please try again.'

Testing

By default, reCAPTCHA is skipped in "test" and "cucumber" env. To enable it during test:

Recaptcha.configuration.skip_verify_env.delete("test")

Alternative API key setup

Recaptcha.configure

# config/initializers/recaptcha.rbRecaptcha.configuredo |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

Recaptcha.with_configuration

For temporary overwrites (not thread-safe).

Recaptcha.with_configuration(site_key:'12345')do# Do stuff with the overwritten site_key.end

Per call

Pass in keys as options at runtime, for code base with multiple reCAPTCHA setups:

recaptcha_tagssite_key:'6Lc6BAAAAAAAAChqRbQZcn_yyyyyyyyyyyyyyyyy'# andverify_recaptchasecret_key:'6Lc6BAAAAAAAAKN3DRm6VA_xxxxxxxxxxxxxxxxx'

hCaptcha support

hCaptcha is an alternative service providing reCAPTCHA API.

To use hCaptcha:

  1. Set a site and a secret key as usual
  2. Set two options inverify_url andapi_service_url pointing to hCaptcha API endpoints.
  3. Disable a response limit check by setting aresponse_limit to the large enough value (reCAPTCHA is limited by 4000 characters).
  4. It is not required to change a parameter name asofficial docs suggest because API handles standardg-recaptcha for compatibility.
# config/initializers/recaptcha.rbRecaptcha.configuredo |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=100000config.response_minimum=100end

hCaptcha uses a scoring system (higher number more likely to be a bot) which is inverse of the reCaptcha scoring system (lower number more likely to be a bot). As such, amaximum_score attribute is provided for use with hCaptcha.

result=verify_recaptcha(maximum_score:0.7)
OptionDescription
:maximum_scoreProvide a threshold to meet or fall below. Threshold should be a float between 0 and 1 which will be tested asscore <= maximum_score. (Default:nil)

Misc


[8]ページ先頭

©2009-2025 Movatter.jp