Implementing Google reCAPTCHA v3 In Angular 14

In this article, we will learn how to add Google reCAPTCHA v3 while registering to an application using angular14.

reCAPTCHA v3 is called when we submit a request on-page, which means when we will click on the register button then reCAPTCHA v3 will be called.

About reCAPTCHA v3

reCAPTCHA is a free service provided by Google. It is used to make a safe website or it prevents the website from spam. The validity of reCAPTCHA v3 is for 2 minutes.

If you are looking for a new reCAPTCHA v3 then we have to re-run the reCAPTCHA v3 verification.

reCAPTCHA v3 returns a score for each request without user interaction.

reCAPTCHA v3 depends on the scoring points between 0.0 and 1.0. if the reCAPTCHA's score is near 1.0 means more trusted users and fewer chances of spam.

To Implement reCAPTCHA v3 functionality first we have to create the google reCAPTCHA account. So, let’s start with creating the reCAPTCHA account.

Google reCAPTCHA Account Setup

To create the Google reCAPTCHA Account, go to this link.

And register for new site, for creating the reCAPTCHA account we have to follow some steps,

  1. First give the Label Name
  2. reCAPTCHA Type (we can select either v2 or v3)
  3. Give the domain name
  4. Give the owner ( email address )
  5. Click on the check box for accepting the term and condition
  6. After giving all the fields click on submit.

After submitting, you will get the site key and secret key, these will be used in our application. The secret key will be used to connect for server site identification, which means verifying whether the user is spam(bot) or not.

Now ReCAPTCHA is ready to use in our application.

Creating an Angular Application

Now let’s create an Angular application

ng new Angular14App

Now open the application in VS code and go to package.json file, you will see latest CLI and other install packages

Now open the terminal and Run the created Application using the below command

ng serve -o

and you will be navigated to http://localhost:4200/ URL and will see the below screen

Go to environment.ts file and put the site_key variable with the reCAPTCHA key.

export const environment = {
    production: false,
    recaptcha: {
        siteKey: 'YOUR_SITE_KEY',
    },
};

Install the ng-recaptcha library.

npm install ng-recaptcha

Configure App.module.ts file

Import the module files and reCAPTCHA files like below,

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormBuilder, FormControl, FormGroup, FormsModule, ReactiveFormsModule, Validators } from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { ReCaptchaService } from './re-captcha.service';
import { HttpClientModule } from '@angular/common/http';
import { RecaptchaV3Module, RECAPTCHA_V3_SITE_KEY } from 'ng-recaptcha';
import { environment } from 'src/environments/environment';
@NgModule({
    declarations: [
        AppComponent
    ],
    imports: [
        BrowserModule,
        AppRoutingModule,
        FormsModule,
        ReactiveFormsModule,
        HttpClientModule,
        RecaptchaV3Module
    ],
    providers: [{
        provide: RECAPTCHA_V3_SITE_KEY,
        useValue: environment.recaptcha.siteKey,
    }, ],
    bootstrap: [AppComponent]
})
export class AppModule {}

Create a Model class

Now create a model class UserRegistrationModel.ts with below fields

export interface UserRegistrationModel {
    UserName: string;
    UserEmailId: string;
    password: string;
    confirmPassword: string;
}

Now open the app.component.html file and place the below code

 <title>Google reCPATCHA Implementation</title>
 <title>Google reCPATCHA Implementation</title>
 <!-- main app container -->
 <div class="card m-3">
   <h5 class="card-header">User Registration</h5>
   <div class="card-body">
     <form [formGroup]="registerForm" (ngSubmit)="onSubmit()">
       <div class="form-row">
         <div class="form-group col-5">
           <label>User Name</label>
           <input type="text" formControlName="UserName" class="form-control" />
         </div>
         <div class="form-group col-5">
           <label>User Email Address</label>
           <input type="text" formControlName="UserEmailId" class="form-control" />
         </div>
       </div>
       <div class="form-row">
         <div class="form-group col">
           <label>Password</label>
           <input type="password" formControlName="password" class="form-control" />
         </div>
         <div class="form-group col">
           <label>Confirm Password</label>
           <input type="password" formControlName="confirmPassword" class="form-control" />
         </div>
       </div>
       <div class="text-center">
         <button class="btn btn-primary mr-1">Register</button>
       </div>
       <div *ngIf="tokenVisible"> reCAPTCHA Token <br />
         <p style="color: red">{{reCAPTCHAToken}}</p>
       </div>
     </form>
   </div>
 </div>

Open the app.component.ts file and put the below code

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { ReCaptchaV3Service } from 'ng-recaptcha';
import { UserRegistrationModel} from '../app/Model/UserRegistrationModel'
import { ReCaptchaService } from './re-captcha.service';
@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
    title = 'Angular14App';
    registerForm!: FormGroup;
    submitted = false;
    reCAPTCHAToken: string = "";
    tokenVisible: boolean = false;
    registrationInfo!: UserRegistrationModel;
    constructor(private formBuilder: FormBuilder, private recaptchaV3Service: ReCaptchaV3Service) {}
    ngOnInit() {
        this.registerForm = new FormGroup({
            UserName: new FormControl(),
            UserEmailId: new FormControl(),
            password: new FormControl(),
            confirmPassword: new FormControl(),
        })
    }
    onSubmit() {
        this.recaptchaV3Service.execute('importantAction').subscribe((token: string) => {
            this.tokenVisible = true;
            this.reCAPTCHAToken = `Token [${token}] generated`;
        });
    }
}

Now run your application, and navigate to http://localhost:4200/, you will see the below page

You will see on the right google reCAPTCHA icon, and it is activated on site

Now give some input to textbox and click on register, and your token is generated. If we get the token means, the button is not clicked by the bot and it is a valid user.