Rails Recaptcha plugin always returns false

2019-04-16 07:40发布

I'm using the rails recaptcha plugin found here: http://github.com/ambethia/recaptcha/tree/master

I have signed up for an account on recaptcha.com, obtained a public & private key, and the site is configured with a global key (for now).

In config/environment.rb I setup the environment variables:

ENV['RECAPTCHA_PUBLIC_KEY'] = 'xxxxxxxxxxxxxxxx'
ENV['RECAPTCHA_PRIVATE_KEY'] = 'XXXXXXXXXXXXXXxx'

In my view I render the captcha like this:

<%= recaptcha_tags %>

And in my controller processing this form I have this:

unless verify_recaptcha #   <--  always returns false
    flash[:error] = "Your captcha entry was invalid"
    render :action=>'new'
    return
end

My problem is that verify_recaptcha always returns false.

I must be missing something simple, but I don't see it. And before I get a smart-alec reply, YES I'm typing the correct words into the captcha box :)

2条回答
唯我独甜
2楼-- · 2019-04-16 07:56

Just as a note, make sure you didn't accidentally switch around the public and private keys; they are different.

I can't tell if you're already handling the possibility that it is correct, in which case you would want to have something like this:

if verify_recaptcha
  @thing.save!
  redirect_to success_path
else
  flash[:error] = "There was an error with the recaptcha code below. Please re-enter the code and click submit." 
  render :action => 'new'
end

And remember to use:

<%= recaptcha_tags :ssl => true %>

If you are using SSL.

查看更多
孤傲高冷的网名
3楼-- · 2019-04-16 08:11

I went in and looked at the recaptcha plugin. The pertinent part reads something like this:

recaptcha = Net::HTTP.post_form URI.parse("http://#{server}/verify"), {
            "privatekey" => private_key,
            "remoteip"   => request.remote_ip,
            "challenge"  => challenge,
            "response"   => response
          }

This takes the challenge and response and returns a response. When I tried it with a challenge and response I generated, I got "true\nsuccess". The following lines of code return false if:

answer, error = recaptcha.body.split.map { |s| s.chomp }
unless answer == "true"

Since I got back "true\nsuccess", answer will be "true", and the code should therefore pass.

Can you try sending the response directly using Net::HTTP and seeing what response you get?

查看更多
登录 后发表回答