What is Google reCAPTCHA?
Google's reCAPTCHA is just a CAPTCHA system that protects your websites or applications from bots and spam. Google's reCAPTCHA can distinguish between an action made by humans and automated action. It's very easy to implement Google reCAPTCHA that's why it is widely used in application and websites which needs some kind of authentication to get protected from bots and spams.
There is two version of Google reCAPTCHA :
We will implement Google reCAPTCHA V3 cause it's the latest, far more secured than Google reCAPTCHA V2.
How Google reCAPTCHA V3 Works?
Google's reCAPTCHA v3 works behind the scenes to determine if the user is a bot or human. It analyzes your behaviour in the background while your scrolling, filling a form or doing something in the website, reCAPTCHA generates a score on user's behaviour and determines if the user is a human or bot.
To Implement Google reCAPTCHA V3 Easily we'll use ng-recaptcha.
ng-recapcha is an npm module which provides a component for implementing Google reCAPTCHA. It provides both Google reCAPTCHA V2 and V3. For this blog, we are implementing Google reCAPTCHA V3 so let's get started.
Prerequisite :
ng-recapcha installation and setup :
npm i ng-recaptcha --save
import { BrowserModule } from "@angular/platform-browser"; import { RECAPTCHA_V3_SITE_KEY, RecaptchaV3Module } from "ng-recaptcha"; import { MyApp } from "./app.component.ts"; @NgModule({ bootstrap: [MyApp], declarations: [MyApp], imports: [BrowserModule, RecaptchaV3Module], providers: [{ provide: RECAPTCHA_V3_SITE_KEY, useValue: "<YOUR_SITE_KEY>" }], }) export class MyAppModule {}
import { ReCaptchaV3Service } from 'ng-recaptcha'; @Component({ selector: 'recaptcha-demo', }) export class RecaptchaV3DemoComponent { constructor( private recaptchaV3Service: ReCaptchaV3Service, ) {} }
import { ReCaptchaV3Service } from 'ng-recaptcha'; @Component({ selector: 'recaptcha-demo', template: ` <button (click)="executeImportantAction()">Important action</button> `, }) export class RecaptchaV3DemoComponent { constructor( private recaptchaV3Service: ReCaptchaV3Service, ) { } public executeImportantAction(): void { this.recaptchaV3Service.execute('importantAction') .subscribe((token) => this.handleToken(token)); }
handleToken(token){ // You can do whatever you want with this token // Example can be used in login/signup // In my case i'm just loggin the token. console.log(token) } }
So that's how we can implement the Google reCAPTCHA V3 in our Angular project.
Thanks.