reCAPTCHA Extension
CmGraphql::Extensions::RecaptchaExtension verifies a reCAPTCHA Enterprise token sent with a mutation before it runs. It adds a required recaptchaToken argument to the mutation's input and calls RecaptchaVerifier against the Enterprise API.
Quick exampleβ
field :login,
mutation: Mutations::Auth::Login,
extensions: [
CmGraphql::Extensions::RecaptchaExtension
]
# With options
field :login,
mutation: Mutations::Auth::Login,
extensions: [
{ CmGraphql::Extensions::RecaptchaExtension => { action: "login", minimum_score: 0.5 } }
]
mutation Login {
login(
input: { email: "user@example.com", recaptchaToken: "recaptcha_token" }
) {
accessToken
expiresAt
}
}
Setupβ
Create a reCAPTCHA Enterprise site and add the keys to your credentials:
gcp:
recaptcha_enterprise_project_id: "your_project_id"
recaptcha_site_key: "your_site_key"
recaptcha_api_key: "your_api_key"
To override the default score globally, set the constant in an initializer:
config/initializers/constants.rb
RECAPTCHA_MINIMUM_SCORE = 0.5
Optionsβ
| Option | Description |
|---|---|
action | The reCAPTCHA action name. Optional when it matches the field name (login above needs no action). |
minimum_score | Minimum score to accept. Defaults to the RECAPTCHA_MINIMUM_SCORE constant. |
How it worksβ
- The extension adds a required
recaptchaToken: Stringargument to the field'sinputtype β clients always send it insideinput. - Before the mutation runs, the token is verified with the Enterprise API. The
actiondefaults to the field name and must match the action the token was issued for. - On failure (missing token, invalid token, action mismatch, low score, or unconfigured credentials) the mutation does not run and a
RecaptchaVerificationFailederror is raised β anunprocessable_entityerror with sub-coderecaptcha_verification_failed.