Using recaptcha with Firebase

18,972

Solution 1

This is a pretty old post, but here's the answer for fellow Google searchers like me. It's now built-in, and super easy to set up:

window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('recaptcha', {
  'callback': (response) => {
    // reCAPTCHA solved, allow signInWithPhoneNumber.
    // ...
  },
  'expired-callback': () => {
    // Response expired. Ask user to solve reCAPTCHA again.
    // ...
  }
})
window.recaptchaVerifier.render()

As tuananh mentions, make sure you add a <div id="recaptcha"></div>.

Solution 2

I've just published a tutorial blog on how to integrate reCAPTCHA in a web site using Firebase Hosting to serve content and Cloud Functions for Firebase to validate the response received from the reCAPTCHA. The function itself looks like this, assuming that the response token is received through the query string:

const functions = require('firebase-functions')
const rp = require('request-promise')

exports.checkRecaptcha = functions.https.onRequest((req, res) => {
    const response = req.query.response
    console.log("recaptcha response", response)
    rp({
        uri: 'https://recaptcha.google.com/recaptcha/api/siteverify',
        method: 'POST',
        formData: {
            secret: 'PASTE_YOUR_SECRET_CODE_HERE',
            response: response
        },
        json: true
    }).then(result => {
        console.log("recaptcha result", result)
        if (result.success) {
            res.send("You're good to go, human.")
        }
        else {
            res.send("Recaptcha verification failed. Are you a robot?")
        }
    }).catch(reason => {
        console.log("Recaptcha request failure", reason)
        res.send("Recaptcha request failed.")
    })
})
Share:
18,972
Vít Kotačka
Author by

Vít Kotačka

Updated on June 17, 2022

Comments

  • Vít Kotačka
    Vít Kotačka about 2 years

    Surprisingly-even more when both are Google products-there is no information that I can find on how to integrate Recaptcha with Firebase. Is it even possible? If not, what can I use to validate humans on a Firebase app that has no auth?