How To Implement Google reCAPTCHA In Angular

How To Implement Google reCAPTCHA In Angular

In this article, we will learn about how to add Google reCAPTCHA to the registration page in the angular application.

When we submit a request on the website, or when we click the register button, reCAPTCHA is activated.

What is Google reCAPTCHA?

Google offers reCAPTCHA as a free service. It is used to establish a secure website or to keep spam off the site. ReCAPTCHA v3 is only valid for two minutes.

We must re-run the reCAPTCHA v3 verification if you are looking for a new reCAPTCHA v3.

Without requiring user input, reCAPTCHA v3 gives a score for each request.

ReCAPTCHA version 3 relies on scores between 0.0 and 1.0. More trustworthy users and lower chances of spam are indicated if the reCAPTCHA score is close to 1.0.

We must first register a Google reCAPTCHA account in order to implement reCAPTCHA v3 capability. Therefore, let's begin by setting up a reCAPTCHA account.

Google reCAPTCHA Account Setup

Visit this link to register for a Google reCAPTCHA account.

In order to create a reCAPTCHA account, we must first register for a new website.

  1. Give the Label Name first.
  2. Type reCAPTCHA (we can select either v2 or v3)
  3. the website's domain name
  4. Dispatch the owner ( email address )
  5. To accept the terms and conditions, tick the box.
  6. Once you've completed all the fields, click submit.

How To Implement Google reCAPTCHA In Angular


We will receive the site key and secret key after submitting; these will be required by our application. The connection for server site identification, which involves determining if the user is spam (bot) or not, will be made using the secret key.

How To Implement Google reCAPTCHA In Angular

ReCAPTCHA is currently prepared for use in our application.

How to Build an Angular Application

Let's now build an Angular application.

ng new reCAPTCHA_Example

Go to the package.json file in the application in VS Code now to see the most recent CLI and other install packages.

How To Implement Google reCAPTCHA In Angular

Open the terminal now and enter the command below to launch the new application.

ng serve -o

and you will be taken to the URL http://localhost:4200, where you will see the screen below.

How To Implement Google reCAPTCHA In Angular


Put the site key variable and the reCAPTCHA key in the environment.ts file.

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

Get the ng-recaptcha library installed.

npm install ng-recaptcha

Add the following code under the app.module.ts file

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 {}

reCAPTCHA files and module files should be imported as shown below.

Now, Create the following fields in the model class UserRegistrationModel.ts.

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

Now, Add the following code to the app.component.html file.

<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>

Put the following code in the app.component.ts file.

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`;
        });
    }
}

Run your application now, then go to http://localhost:4200/ to see the page below

How To Implement Google reCAPTCHA In Angular

The Google reCAPTCHA icon is shown on the right and is turned on for this particular page.

After entering some information in the textbox and clicking "register," your token will be produced. If we receive the token, it confirms that a real person, not a bot, clicked the button.

How To Implement Google reCAPTCHA In Angular

Conclusion

In this article, we learned how to add Google reCAPTCHA to the registration page in the angular application with a simple example.

I hope this article helps you and you will like it.👍

If you have any doubt or confusion then free to ask in the comment section.

Post a Comment

Previous Post Next Post