DethAriel / ng-recaptcha

Angular component for Google reCAPTCHA
https://dethariel.github.io/ng-recaptcha/
MIT License
475 stars 128 forks source link

Invalid site key or not loaded in api.js #295

Closed xinthose closed 1 year ago

xinthose commented 1 year ago

Sometimes my users get this error Invalid site key or not loaded in api.js XXXXXXXXXX from my website when I call the recaptchaV3Service.execute method. What fixes it is, they have to clear their cache for all time, reload the webpage, and try again, then it works. I never get the issue from my computer, so this is hard to replicate/solve. The site key shown in the console error is the correct one for my website/domain.

I am using Google reCaptcha v3. ng-recaptcha version 12.0.1.

app.modules.ts

import { RECAPTCHA_V3_SITE_KEY, RecaptchaV3Module } from "ng-recaptcha";

@NgModule({
  imports: [
    RecaptchaV3Module,
  ],
  providers: [
    {
      provide: RECAPTCHA_V3_SITE_KEY,
      useValue: environment.production ? config.google.prod.recaptchaSiteKey : config.google.dev.recaptchaSiteKey
    },
  ]
})
export class AppModule { }

login.component.ts

import { ReCaptchaV3Service } from "ng-recaptcha";

@Component({
})
export class LoginComponent {

    constructor(
        private recaptchaV3Service: ReCaptchaV3Service,
    ) { }

    async login() {
        // do stuff

        const token: string = await this.checkGoogleRecaptcha();  // get token
        const response = await this.googleService.checkRecaptcha(token); // check server side
    }

    checkGoogleRecaptcha(): Promise<any> {
        return new Promise((resolve, reject) => {
            this.recaptchaV3Service.execute("login").subscribe({
                next: (token: string) => {
                    resolve(token);
                },
                error: (error: any) => {
                    reject(error);
                }
            });
        });
    }
}
xinthose commented 1 year ago

Possibly related SO post.

xinthose commented 1 year ago

Nevermind. I stopped using this library and use the generic code instead. No more issues.

npm i @types/grecaptcha

<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <title>Portapay.com</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="referrer" content="strict-origin">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <script src="https://www.google.com/recaptcha/api.js?render=asfasdfsdfdd324234234"></script>
</head>

<body>
  <app-root></app-root>
</body>

</html>
import "node_modules/@types/grecaptcha/index.d.ts";

const token: string = await grecaptcha.execute("asfasdfsdfdd324234234", { action: "login" });

// verify token server side