重新验证 gem 错误 "No site key specified."

Recaptcha gem error "No site key specified."

我正尝试按照文档中的描述在我的 rails 5 应用程序中设置 Recaptcha,但它失败了。

我使用这个 gem:recaptcha (4.6.6)ruby 2.5.0rails 5.1.4

在视图中:

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

在设计注册控制器中:

  prepend_before_action :check_captcha, only: :create

  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
      respond_with_navigational(resource) { redirect_to new_user_registration_path }
    end 
  end

在我的 initializers/recaptcha.rb

Recaptcha.configure do |config|
  config.site_key   = Rails.application.config_for(:recaptcha)['site_key']
  config.secret_key = Rails.application.config_for(:recaptcha)['secret_key']
end

在我的 recaptcha.yml:

default: &default
  site_key: <%= ENV["RECAPTCHA_SITE_KEY"] %>
  secret_key: <%= ENV["RECAPTCHA_SECRET_KEY"] %>

development:
  <<: *default

test:
  <<: *default

staging:
  <<: *default

production:
  <<: *default

在/etc/environments中:

# RECAPTCHA
RECAPTCHA_SITE_KEY=6Lfg3ksUAAAAABOD_OXCtPO60*******
RECAPTCHA_SECRET_KEY=6Lfg3ksUAAAAAOmFGdAxdo8*******

问题

/etc/environments 添加 ENV 变量后,我用这个命令导出它:

for line in $( cat /etc/environment ) ; do export $line ; done

然后我检查Recaptcha模块是否配置正确:

/home/deploy/apps/app_name/current$ bundle exec rails c
Loading staging environment (Rails 5.1.4) 
2.5.0 :001 > Recaptcha::Configuration.new
 => #<Recaptcha::Configuration:0x0000000006601908 @skip_verify_env=["test", "cucumber"], @handle_timeouts_gracefully=true, @secret_key="6Lfg3ksUAAAAAOmFGdAxdo8H*************", @site_key="6Lfg3ksUAAAAABOD_OXCtPO*************"> 
2.5.0 :002 > Recaptcha::Configuration.new.site_key!
 => "6Lfg3ksUAAAAABOD_OXCtPO*************" 

此外,我在 运行 printenv 命令时看到了这些 ENV 变量(所以它真的被加载了)

之后,我重新启动rails并得到一个错误

No site key specified.

/home/deploy/apps/app_name/shared/bundle/ruby/2.5.0/gems/recaptcha-4.6.6/lib/recaptcha/configuration.rb:47:in `site_key!'
/home/deploy/apps/app_name/shared/bundle/ruby/2.5.0/gems/recaptcha-4.6.6/lib/recaptcha/client_helper.rb:79:in `recaptcha_components'
/home/deploy/apps/app_name/shared/bundle/ruby/2.5.0/gems/recaptcha-4.6.6/lib/recaptcha/client_helper.rb:15:in `recaptcha_tags'
/home/deploy/apps/app_name/releases/20180310222304/app/views/users/registrations/new.html.erb:27:in `block in _app_views_users_registrations_new_html_erb___216558772140569572_69973306795360'
/home/deploy/apps/app_name/shared/bundle/ruby/2.5.0/gems/actionview-5.1.4/lib/action_view/helpers/capture_helper.rb:39:in `block in capture'
/home/deploy/apps/app_name/shared/bundle/ruby/2.5.0/gems/actionview-5.1.4/lib/action_view/helpers/capture_helper.rb:203:in `with_output_buffer'
/home/deploy/apps/app_name/shared/bundle/ruby/2.5.0/gems/actionview-5.1.4/lib/action_view/helpers/capture_helper.rb:39:in `capture'
/home/deploy/apps/app_name/shared/bundle/ruby/2.5.0/gems/actionview-5.1.4/lib/action_view/helpers/form_helper.rb:450:in `form_for'
/home/deploy/apps/app_name/releases/20180310222304/app/views/users/registrations/new.html.erb:21:in `_app_views_users_registrations_new_html_erb___216558772140569572_69973306795360'
/home/deploy/apps/app_name/shared/bundle/ruby/2.5.0/gems/actionview-5.1.4/lib/action_view/template.rb:157:in `block in render'

我仍然不知道 "No site key specified" 错误的原因。

我真的不喜欢 gem 'recapthca' 直接使用 ENV 变量,

而且我花太多时间在调查上。

所以,我决定不使用这个 gem 并编写自己的代码。

我在申请中只使用 Invisible Recaptcha

配置文件(加载秘密和站点密钥)

# /config/recaptcha.yml
default: &default
  site_key: <%= ENV["RECAPTCHA_SITE_KEY"] %>
  secret_key: <%= ENV["RECAPTCHA_SECRET_KEY"] %>

development:
  <<: *default

test:
  <<: *default

staging:
  <<: *default

production:
  <<: *default

应用程序助手(带有 Recaptcha 助手的按钮)

# /app/helpers/application_helper.rb
module ApplicationHelper
  def submit_with_recaptcha(text, custom_options)
    unless custom_options[:data].has_key?(:form_id) 
      raise "Data Form Id option not found ('{data: {form_id: 'id_without_dash'}')."
    end

    options = {
      type: 'button',
      data: {
        form_id: custom_options[:data][:form_id],
        sitekey: recaptcha_site_key,
        callback: "submit#{custom_options[:data][:form_id].camelize}#{Time.current.to_i}"
      },
      class: (custom_options[:class].split(' ') + ['g-recaptcha']).uniq.join(' ')
    }

    script_code = <<-SCRIPT
      function #{options[:data][:callback]}() {
        document.getElementById('#{options[:data][:form_id]}').submit();
      }
    SCRIPT

    javascript_tag(script_code) + content_tag(:div, class: 'recaptcha_wrapper'){ submit_tag(text, options) }
  end

  private

  def recaptcha_site_key
    Rails.application.config_for(:recaptcha)['site_key']
  end
end

验证服务(因为它使用外部API)

# app/services/google_recaptcha/verification.rb
module GoogleRecaptcha
  # https://developers.google.com/recaptcha/docs/verify
  class Verification
    # response - params['g-recaptcha-response'])
    def self.successful?(recaptcha_params, remoteip)
      verify_url = URI.parse('https://www.google.com/recaptcha/api/siteverify')
      verify_request = Net::HTTP::Post.new(verify_url.path)

      verify_request.set_form_data(
        response: recaptcha_params,
        secret: secret_key,
        remoteip: remoteip
      )

      connection = Net::HTTP.new(verify_url.host, verify_url.port)
      connection.use_ssl = true

      Rails.logger.info '[RECAPTCHA] Sending verification request.'

      verify_response = connection.start { |http| http.request(verify_request) }
      response_data = JSON.parse(verify_response.body)

      Rails.logger.info "[RECAPTCHA] Verification response is#{' not' unless response_data['success']} successful."

      response_data['success']
    end

    private

    def self.secret_key
      Rails.application.config_for(:recaptcha)['secret_key']
    end
  end
end

Controller Concern(before_action 中的 Recaptcha 验证)

# app/controllers/concerns/recaptchable.rb
module Recaptchable
  extend ActiveSupport::Concern

  included do
    before_action :verify_recaptcha, only: [:create]
  end

  private

  def verify_recaptcha
    unless GoogleRecaptcha::Verification.successful?(recaptcha_params['g-recaptcha-response'], request.remote_ip)
      render :new
      return
    end
  end

  def recaptcha_params
    params.permit(:'g-recaptcha-response')
  end
end

用法

关注你的控制器:

class MyController < ShopController
  include Recaptchable
end

www.google.com/recaptcha/api.js javascript 添加到您的页面

submit_with_recaptcha 助手添加到您的表单中

<%= form_for @delivery, url: users_delivery_path, method: 'post' do |f| %>
  <%= submit_with_recaptcha t('order.deliver.to_confirmation'), data: {form_id: 'new_delivery'}, class: 'btn-round' %>

<% end %>
<%= javascript_include_tag "https://www.google.com/recaptcha/api.js?hl=#{I18n.locale}", 'data-turbolinks-track': 'reload' %>

就是这样。

注意:我将此答案发布在这里,供可能会发现此问题的人使用。这是我解决问题的方法。

我使用 local_env.yml 作为我的环境变量。我刚开始使用 gem 并将 RECAPTCHA_SITE_KEY & RECAPTCHA_SECRET_KEY 添加到 local_env.yml。我得到了同样的错误。

花了一点时间才发现 gem 直接使用了变量。我最终将以下语句放在 ~/.bashrc 中,类似于文档中所说的,但没有在值周围加上引号。

export RECAPTCHA_SITE_KEY=6Lc6BAAAAAAAAChqRbQZcn_yyyyyyyyyyyyyyyyy
export RECAPTCHA_SECRET_KEY=6Lc6BAAAAAAAAKN3DRm6VA_xxxxxxxxxxxxxxxxx

我在 Heroku 上托管我的应用程序。我执行了以下终端命令以在 Heroku 中设置我的环境变量。

heroku config:set RECAPTCHA_SITE_KEY=‘6Lc6BAAAAAAAAChqRbQZcn_yyyyyyyyyyyyyyyyy’
heroku config:set RECAPTCHA_SECRET_KEY=‘6LcGuI4U6Lc6BAAAAAAAAKN3DRm6VA_xxxxxxxxxxxxxxxxxAAAAGAWMYRKFGfHUCSD0SPrMX2lfyl9’

你在使用 nginx 吗? Nginx 删除了 ENV 变量(TZ 除外),似乎 recaptcha gem 对此特别敏感。根据经验,当使用 dotenv gem 其他 ENV 变量工作正常时,recaptcha ENV 变量将被忽略。

您可以通过将环境变量添加到 nginx.conf 的顶部来解决问题。

env RECAPTCHA_SITE_KEY=value1;
env RECAPTCHA_SECRET_KEY=value2;

Here's nginx's documentation on the matter.

我在这里发帖,以防有人正在寻找 Rails 5.2 解决方案来设置 Recaptcha 密钥。此解决方案使用新的 config/master.key 和 config/credentials.yml.enc 加密文件。

  1. 将 Recaptcha 密钥添加到凭据。yml.enc 通过在本地终端中编辑文件的文件:

    EDITOR="vim" rails credentials:edit

  2. 将密钥添加到凭据文件后(参见下面的示例),保存并退出文件。退出后,credentials.yml.enc 文件将自动加密。 master.key 是您的应用程序解密所必需的。加密前:

    recaptcha_site_key: 6Lc6BAAAAAAAAChqRbQZcn_yyyyyyyyyyyyyyyyy recaptcha_secret_key: 6Lc6BAAAAAAAAKN3DRm6VA_xxxxxxxxxxxxxxxx


3. 在您的 Rails 应用程序中创建一个名为 config/recaptcha.rb 的文件,并向其中添加以下代码:
Recaptcha.configure do |config| config.site_key = Rails.application.credentials.dig(:recaptcha_site_key) config.secret_key = Rails.application.credentials.dig(:recaptcha_secret_key) end

此解决方案在本地和 Ubuntu/nginx 生产中有效。您不需要 gem 或环境变量即可工作。如果 master.key 解密失败,您可能需要同时删除 credentials.yml.enc 文件,甚至 master.key 文件,然后在本地重复此过程(EDITOR="vim" rails credentials:edit,等等),然后将新的 master.key 复制到生产环境并重新部署。