Angular Google reCAPTCHA

Below are the instructions to quickly set up the Google reCAPTCHA where needed. Here we use the ng-recaptcha package to do most of the heavy lifting where the code below will handle the rest.

What is Google reCAPTCHA?

Google reCAPTCHA is a free service by Google that protects websites and applications from automated abuse such as spam and brute‑force attacks. It uses advanced risk analysis techniques to distinguish between human users and bots. There are two primary versions used in modern web apps:

reCAPTCHA v2

  • User Interaction: Presents a challenge that users must complete, typically a checkbox labeled “I’m not a robot,” or an image‑selection task when higher risk is detected.
  • Flow:

    1. The widget loads on the page.
    2. The user clicks the checkbox (or the widget triggers invisible verification).
    3. If Google’s risk analysis is uncertain, an additional image puzzle is shown.
    4. On completion, a token is generated and passed back to your application.
  • Use Cases: Simple form submissions, login pages, comment sections—where explicit user interaction is acceptable.

reCAPTCHA v3

  • No User Interaction: Runs entirely in the background and assigns a score (0.0–1.0) based on user behavior and risk factors.
  • Flow:

    1. Your application calls the v3 API to “execute” an action (e.g., login, submit_form).
    2. Google returns a token containing a risk score.
    3. You evaluate the score on your server against a threshold to accept or flag the request.
  • Use Cases: High‑traffic sites, continuous monitoring (e.g., API endpoints, AJAX requests) where frictionless UX is critical.

What is ng-recaptcha?

ng-recaptcha is an Angular wrapper for Google’s reCAPTCHA API. It provides:

  • Angular components and directives for both v2 and v3.
  • Easy configuration via dependency injection.
  • Observable-based events for token retrieval and error handling.

Prerequisites

  1. Google API Keys: Register your site at Google reCAPTCHA Admin Console and obtain the Site Key and Secret Key.
  2. Angular Project: Angular CLI v12 or higher.

Installation

Install the ng-recaptcha package:

npm install ng-recaptcha

Configuration

1. Provide Your Site Key

In your AppModule, import the module and register your site key:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RecaptchaModule, RecaptchaFormsModule } from 'ng-recaptcha';

@NgModule({
  imports: [
    BrowserModule,
    RecaptchaModule,
    RecaptchaFormsModule
  ],
  providers: [
    {
      provide: RECAPTCHA_V3_SITE_KEY,
      useValue: 'YOUR_SITE_KEY_HERE'
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

If you plan to use reCAPTCHA v3, also import RecaptchaV3Module:

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

@NgModule({
  imports: [RecaptchaV3Module],
  providers: [
    {
      provide: RECAPTCHA_V3_SITE_KEY,
      useValue: 'YOUR_V3_SITE_KEY'
    }
  ]
})
export class AppModule {}

Usage in Template

reCAPTCHA v2 Checkbox

<form (ngSubmit)="onSubmit()" #demoForm="ngForm">
  <!-- other form fields -->
  <re-captcha
    siteKey="YOUR_SITE_KEY_HERE"
    (resolved)="onCaptchaResolved($event)">
  </re-captcha>
  <button type="submit" [disabled]="!captchaToken">Submit</button>
</form>

reCAPTCHA v3 (Score-Based)

<button (click)="executeAction()">Perform Action</button>

Component Logic

import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import {
  ReCaptchaV3Service
} from 'ng-recaptcha';

@Component({
  selector: 'app-contact',
  templateUrl: './contact.component.html'
})
export class ContactComponent {
  captchaToken: string | null = null;

  constructor(
    private fb: FormBuilder,
    private recaptchaV3Service: ReCaptchaV3Service
  ) {}

  onCaptchaResolved(token: string): void {
    this.captchaToken = token;
  }

  executeAction(): void {
    this.recaptchaV3Service.execute('importantAction')
      .subscribe((token: string) => {
        // send token with your request
        this.captchaToken = token;
      });
  }

  onSubmit(): void {
    if (!this.captchaToken) {
      return;
    }

    // send form data and captchaToken to backend
  }
}

Workflow

Below is a high-level flow of how reCAPTCHA integrates into your Angular form:

flowchart LR A[User opens form] --> B[reCAPTCHA widget renders] B --> C[User completes CAPTCHA] C --> D[Angular captures token] D --> E[Component sends token + data to server] E --> F[Server verifies token with Google] F --> G{Verification result} G -->|Valid| H[Proceed with request] G -->|Invalid| I[Return error to user]

Server-Side Verification (C#)

On your backend (ASP.NET Core example), use the following code to verify the token with Google:

using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;

public class RecaptchaVerificationResponse
{
    [JsonProperty("success")]
    public bool Success { get; set; }

    [JsonProperty("score")]
    public float Score { get; set; }

    [JsonProperty("action")]
    public string Action { get; set; }

    [JsonProperty("challenge_ts")]
    public string ChallengeTimestamp { get; set; }

    [JsonProperty("hostname")]
    public string Hostname { get; set; }
}

public class RecaptchaService
{
    private readonly HttpClient _httpClient;
    private readonly string _secretKey;

    public RecaptchaService(HttpClient httpClient, IConfiguration configuration)
    {
        _httpClient = httpClient;
        _secretKey = configuration["Recaptcha:SecretKey"];
    }

    public async Task<bool> VerifyTokenAsync(string token)
    {
        var response = await _httpClient.PostAsync(
            $"https://www.google.com/recaptcha/api/siteverify?secret={_secretKey}&response={token}",
            null
        );

        if (!response.IsSuccessStatusCode)
            return false;

        var json = await response.Content.ReadAsStringAsync();
        var result = JsonConvert.DeserializeObject<RecaptchaVerificationResponse>(json);

        // For v3, you may also check result.Score and result.Action
        return result != null && result.Success;
    }
}

You can then inject RecaptchaService into your controller or service and call VerifyTokenAsync(token) before processing sensitive requests.

Best Practices

  • Keep your Secret Key secure: Never expose it in frontend code.
  • Validate on server: Client-side checks alone are not sufficient.
  • Handle failures gracefully: Provide clear messaging when verification fails.
  • Use v3 for seamless UX: Customize score thresholds based on your risk.

With these steps, you can quickly add robust bot protection to your Angular applications using Google reCAPTCHA and the ng-recaptcha library.