在Firebase Function中验证reCAPTCHA v3会导致CORS问题 [英] Verifying reCAPTCHA v3 in Firebase Function causes CORS Issue

查看:59
本文介绍了在Firebase Function中验证reCAPTCHA v3会导致CORS问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码可以验证导致 CORS 问题的Firebase功能中的 Google reCAPTCHA v3 :

  const函数= require('firebase-functions');const nodemailer = require("nodemailer");const express = require("express");const cors = require("cors");const request = require('request');const serverApi = express();api.use(cors({origin:true}));函数verifyCaptcha(token,returnData){//将您的秘密密钥放在这里.var secretKey = functions.config().recaptcha.secretkey;var VerificationUrl ="https://www.google.com/recaptcha/api/siteverify?secret=" + secretKey +& response =" +令牌;//在这里注意:外部网络对google.com的呼叫request(verificationUrl,function(error,response,body){body = JSON.parse(body);//成功与否取决于验证码验证.如果(!body.success){body ['status'] = false;body ['errSource'] =验证码";body ['message'] =无法通过验证码验证.";} 别的 {body ['status'] = true;body ['message'] =已成功通过验证码验证!";};console.log(`Google返回:$ {JSON.stringify(body)}`);returnData(body);});};api.post("/api/service-name",(req,res)=> {如果(!req.body ['g-recaptcha-response']){return res.send({"status":false,"errSource":"recaptcha","message":未找到客户端reCAPTCHA令牌."});};const recaptchaToken = req.body ['g-recaptcha-response'];verifyCaptcha(recaptchaToken,函数(结果){如果(result.status == false){返回res.send(result);};//我的业务逻辑在这里.});});Exports.api =函数.https.onRequest(api); 

我注意到,在Firebase函数中删除reCAPTCHA v3验证请求后,本地主机不再使用 $.ajax调用"/api/service-name" 的CORS问题().这是因为以下Firebase功能日志使我想起了无法访问外部网络" :

 未配置结算帐户.无法访问外部网络,并且配额受到严格限制.配置计费帐户以消除这些限制 

我的问题是:有没有一种方法可以使我的服务器端reCAPTCHA验证正常运行而不会导致此CORS问题,可以通过未配置结算帐户"来防止此问题?谢谢!

更新:

在捕获到执行验证的 request()错误后,出现以下错误:

  {errno:"EAI_AGAIN",代码:"EAI_AGAIN",系统调用:"getaddrinfo",主机名:"www.google.com",主机:"www.google.com",……} 

此外,在处理了此错误之后,不再出现CORS问题,但是仍然无法验证reCAPTCHA.知道是什么原因造成的吗?再次感谢!

解决方案

I have the following codes that verify Google reCAPTCHA v3 in my Firebase Function that caused the CORS issue:

const functions = require('firebase-functions');
const nodemailer = require("nodemailer");
const express = require("express");
const cors = require("cors");
const request = require('request');
const serverApi = express();

api.use(cors({ origin: true }));

function verifyCaptcha(token, returnData) {
    // Put your secret key here.
    var secretKey = functions.config().recaptcha.secretkey;

    var verificationUrl = "https://www.google.com/recaptcha/api/siteverify?secret=" + secretKey + "&response=" + token;

    // Note here: External network call to google.com
    request(verificationUrl, function (error, response, body) {
        body = JSON.parse(body);
        // Success will be true or false depending upon captcha validation.
        if (!body.success) {
            body['status'] = false;
            body['errSource'] = "recaptcha";
            body['message'] = "Failed to pass captcha verification.";

        } else {
            body['status'] = true;
            body['message'] = "Successfully passed captcha verification!";

        };
        console.log(`Google returns: ${JSON.stringify(body)}`);

        returnData(body);
    });
};

api.post("/api/service-name", (req, res) => {
    if (!req.body['g-recaptcha-response']) {
        return res.send({ "status": false, "errSource": "recaptcha", "message": "Client-side reCAPTCHA token not found." });
    };

    const recaptchaToken = req.body['g-recaptcha-response'];

    verifyCaptcha(recaptchaToken, function (result) {
        if (result.status == false) {
            return res.send(result);
        };

        // My business logics here.

    }); 
});

exports.api = functions.https.onRequest(api);

I noticed that after removing the reCAPTCHA v3 verification request in within my Firebase Function, no more CORS issue for my localhost to call "/api/service-name" using $.ajax(). This is because the following Firebase Function log reminded me of the "External network is not accessible":

Billing account not configured. External network is not accessible and quotas are severely limited.
Configure billing account to remove these restrictions

My question is: Is there a way to get my server-side reCAPTCHA verification to work without causing this CORS issue, which could be prevented by "Billing account not configured"? Thanks!

UPDATE:

After catching the request() error that does the verification, I get the following error:

{errno: "EAI_AGAIN", code: "EAI_AGAIN", syscall: "getaddrinfo", hostname: "www.google.com", host: "www.google.com", …}

Also, after handling this error, no more CORS issue, but reCAPTCHA still cannot be verified. Any idea what causes this? Thanks again!

解决方案

It's now confirmed that the above issue has been resolved after Enable Billing at the Google Cloud Console. It is NOT actually the CORS issue between the localhost and Firebase Functions/Hosting (although the Chrome browser returned as CORS related error message), it's actually the HTTP Request from the Firebase Function to the Google reCAPTCHA api during token verification process. Due to billing account not linked to the Firebase Project where the function sits in, any requests from any Firebase Functions to any External Network Resources, including Google reCAPTCHA, will be rejected with the following errors:

HTTP Request Error:

{errno: "EAI_AGAIN", code: "EAI_AGAIN", syscall: "getaddrinfo", hostname: "www.google.com", host: "www.google.com", …}

After enabling billing at GCP and linking the billing account to the specific Firebase Project, the request to Google reCAPTCHA verification will be successful (if the token is valid) without the above error. However, your FREE Spark Tier Firebase account will be AUTOMATICALLY UPGRADED to Blaze Plan -- Pay as you go.

这篇关于在Firebase Function中验证reCAPTCHA v3会导致CORS问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆