簡體   English   中英

Recaptcha gem錯誤“未指定站點密鑰。”

[英]Recaptcha gem error “No site key specified.”

我正在嘗試在Rails 5應用程序中設置Recaptcha,如文檔中所述,但失敗。

我使用以下寶石: 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

在我的初始值設定項/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*******

問題

將ENV變量添加到/etc/environments ,我使用以下命令將其導出:

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並出現錯誤

未指定站點密鑰。

/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'

如果有人正在尋找Rails 5.2解決方案來設置Recaptcha密鑰,我將在此處發布。 該解決方案利用了新的config / master.key和config / credentials.yml.enc加密文件。

  1. 通過在本地終端中編輯Recaptcha密鑰,將其添加到certificate.yml.enc文件中:

    EDITOR="vim" rails credentials:edit

  2. 將密鑰添加到憑據文件后(請參見下面的示例),保存並退出文件。 退出后,然后將自動對certificate.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解密失敗,則可能需要刪除certificate.yml.enc文件,甚至可能要刪除master.key文件,然后在本地重復此過程(EDITOR =“ vim” rails certificate:edit等)。在復制新的master.key以進行生產和重新部署之前。

我仍然不知道“未指定站點密鑰”錯誤的原因是什么。

我真的不喜歡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

控制器問題 (before_action中的驗證碼驗證)

# 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。 我遇到了同樣的錯誤。

花了一點時間才知道寶石直接使用了變量。 我最終將以下語句放在~/.bashrc類似於文檔中所說的內容,但在值~/.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除外),並且recapcha寶石似乎對此特別敏感。 根據經驗,當使用dotenv gem時,其他ENV變量正常工作時,recaptcha ENV變量將被忽略。

您可以通過將env vars添加到nginx.conf的頂部來解決該問題。

env RECAPTCHA_SITE_KEY=value1;
env RECAPTCHA_SECRET_KEY=value2;

這是Nginx關於此事的文檔。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM