Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid input response and secret when verifying google reCaptcha

I am really struggling to get a successful response when doing a post request to the google recaptcha api. I am receiving the following response:

{
  "success": false,
  "error-codes": [
    "invalid-input-response",
    "invalid-input-secret"
  ]
}

I had a look at reCAPTCHA - error-codes: 'missing-input-response', 'missing-input-secret' when verifying user's response (missing details on POST) and followed the answer as closely as possible but with no success.

Here is my file below:

var request = require('request');

module.exports = {
  verifyCaptcha: function(req, res) {

    var secret = 'SECRET_KEY';
    var response = JSON.stringify(req.body.response);
    request({
        url: 'https://www.google.com/recaptcha/api/siteverify',
        method: 'POST',
        headers: { "Content-Type": "application/x-www-form-urlencoded" },
        body: `secret=${secret}&response=${response}`,
    }, function (err, response, body) {
        if (err) {
            res.status(500).send({
                error: "Could not verify captcha"
            });
        } else {
            res.status(200).send({
                message: body
            });
        }
    });
  },
}

If anyone has a solution to this problem please let me know!

like image 983
Simon Jackson Avatar asked Feb 14 '19 16:02

Simon Jackson


2 Answers

Due to the docs: https://developers.google.com/recaptcha/docs/verify

invalid-input-secret: The secret parameter is invalid or malformed. Maybe you have mixed the site_key and the secret_key.

like image 124
Máté Gregor Avatar answered Sep 20 '22 20:09

Máté Gregor


You need to add the user remote IP address.

var user_ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
request({
    url: 'https://www.google.com/recaptcha/api/siteverify',
    method: 'POST',
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
    body: `secret=${secret}&response=${response}&remoteip=${user_ip}`}...

Another thing I see that you are not using template literal, you should change the quotes to ` instead of '.

OR, You should use a ready-made module for reCaptcha, like this one:

https://www.npmjs.com/package/recaptcha

like image 32
arielb Avatar answered Sep 21 '22 20:09

arielb