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

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

问题描述

我的 Firebase 函数中有以下代码验证 Google reCAPTCHA v3,导致 CORS 问题:

const functions = require('firebase-functions');常量 nodemailer = 要求(nodemailer");常量表达 = 要求(表达");常量 cors = 要求(cors");const request = require('request');常量 serverApi = express();api.use(cors({ origin: true }));功能验证验证码(令牌,返回数据){//把你的密钥放在这里.var secretKey = functions.config().recaptcha.secretkey;var verifyUrl = "https://www.google.com/recaptcha/api/siteverify?secret=" + secretKey + "&response=" + token;//注意这里:外部网络调用 google.comrequest(verificationUrl, function (error, response, body) {正文 = JSON.parse(正文);//成功将根据验证码验证为真或假.如果(!body.success){身体['状态'] =假;body['errSource'] = "recaptcha";body['message'] = "验证码验证失败.";} 别的 {身体['状态'] =真;body['message'] = "成功通过验证码!";};console.log(`谷歌返回:${JSON.stringify(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,函数(结果){if (result.status == false) {返回 res.send(结果);};//我的业务逻辑在这里.});});export.api = 函数.https.onRequest(api);

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

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

我的问题是:有没有办法让我的服务器端 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 函数中验证 reCAPTCHA v3 会导致 CORS 问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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