Search code examples
reactjsfirebasefirebase-authenticationrecaptchamulti-factor-authentication

Unable to set up invisible reCAPTCHA verifier for multi-factor authentication in a react app


As per this article, https://cloud.google.com/identity-platform/docs/web/mfa, I am trying to set up invisible reCAPTCHA. However, the callback function does not seem to fire. The idea is that I want the recaptcha to fire off upon a button click and send a code via the callback function but it is not working.

I am trying to activate the recaptcha via the following function linked to a button with the 'code-button" id.

sendCode () {         
         
        const recaptchaVerifier = new firebase.auth.RecaptchaVerifier('code-button', {
            'size': 'invisible',            
            'callback': () => {
              // reCAPTCHA solved, you can proceed with phoneAuthProvider.verifyPhoneNumber(...).
            //   onSolvedRecaptcha();
            console.log("captcha is working")
            }            
           })
               
            recaptchaVerifier.render()               
                 
     }

When I press the button to fire off the sendCode function, the callback inside the recaptchaVerifier does not seem to work. It is supposed to console.log "captcha working" but it does not as I check the console.

I do get the following issues in the console but I am not sure if they are actually blocking the callback or making the recaptcha not work:

Indicate whether to send a cookie in a cross-site request by specifying its SameSite attribute

SharedArrayBuffer usage is restricted to cross-origin isolated sites

I do not even know how to resolve them. As per some articles, they seem to be issues that can only be resolved by Google itself.

Does anyone know why this is happening?

Thanks.


Solution

  • I solved this issue myself by dropping the callback from within and instead I simply called recaptchaVerifier from another function as needed. For example:

    First, initialize the recaptcha and render it:

    const recaptchaVerifier = new firebase.auth.RecaptchaVerifier('code-button', {
                        size: 'invisible'                    
                       });
    
                       recaptchaVerifier.render()
    

    Then, simply call it where needed:

    user.multiFactor.getSession().then((multiFactorSession) => {
                        // Specify the phone number and pass the MFA session.
                        const phoneInfoOptions = {
                          phoneNumber: this.state.number,
                          session: multiFactorSession
                        };
                        
                        const phoneAuthProvider = new firebase.auth.PhoneAuthProvider();
                        // Send SMS verification code.
                        return phoneAuthProvider.verifyPhoneNumber(
                            phoneInfoOptions, recaptchaVerifier);
                      })