DEV Community

Cover image for Adding the AWS WAF CAPTCHA to an Angular application
Rodrigo Kamada
Rodrigo Kamada

Posted on

Adding the AWS WAF CAPTCHA to an Angular application

Introduction

In this article, we will create a WEB application using the latest version of Angular and integrate the AWS WAF (Web Application Firewall) CAPTCHA challenge to protect against bots.

Prerequisites

Before we begin, you need to install and configure the tools below to create the Angular application and integrate it with the AWS WAF captcha.

  • Node.js and npm: Node.js is a JavaScript code runtime software based on Google's V8 engine. npm is a package manager for Node.js (Node.js Package Manager). They will be used to build and run the Angular application and install the libraries.
  • Angular CLI: Angular CLI is a command line utility tool for Angular and it will be used to create the base structure of the Angular application.
  • IDE (e.g. Visual Studio Code or WebStorm): IDE (Integrated Development Environment) is a tool with a graphical interface to help in the development of applications and it will be used to develop the Angular application.
  • AWS Account: Amazon Web Services is a cloud computing services platform and it will be used to integrate the AWS WAF CAPTCHA challenge.

Getting started

Create and configure the account on AWS WAF

AWS WAF (Web Application Firewall) is a security service designed to protect your WEB applications and APIs from exploits of common internet vulnerabilities and bots that can affect availability, compromise security, or consume excessive resources.

1. Let's access the AWS account. Access the site https://aws.amazon.com/waf/ and click on the link Sign in to console.

Amazon WAF - Home page

Note:

2. Now we will fill in the field Account ID or alias, fill in the field IAM username, fill in the field Password and click on the button Sign in.

Amazon WAF - IAM user sign in

3. Next, we will type waf in the search field and click on the option WAF & Shield.

Amazon WAF - Console Home

4. Then, we will click on the menu Application integration.

Amazon WAF - WAF & Shield

5. After click on the menu Application integration, we will click on the tab CAPTCHA integration.

Amazon WAF - Application integration

6. Now we will click on the option CloudFront JavaScript tag, click on the button Copy JavaScript tag to copy the URL of the JavaScript file because this URL will be configured in the Angular application and click on the button Generate API key.

Amazon WAF - CAPTCHA integration

7. Next, we will click on the option CloudFront, fill in the field Domain with your website's domain and click on the button Generate API key.

Amazon WAF - Generate API key

8. Then, we will click on the icon to copy the API key beacuse this API key will be configured in the Angular application.

Amazon WAF - WAF & Shield

9. Ready! The API key was created.

Create the Angular application

Angular is a development platform for building WEB, mobile and desktop applications using HTML, CSS and TypeScript (JavaScript). Currently, Angular is at version 21 and Google is the main maintainer of the project.

1. Let's create the application with the Angular base structure using the @angular/cli tool with the AI configuration files disabled, the server-side rendering (SSR) disabled, the route file disabled and the SCSS style format.

ng new angular-aws-waf-captcha --ai-config=none --ssr=false --routing=false --style=scss
CREATE angular-aws-waf-captcha/README.md (1473 bytes)
CREATE angular-aws-waf-captcha/.editorconfig (314 bytes)
CREATE angular-aws-waf-captcha/.gitignore (604 bytes)
CREATE angular-aws-waf-captcha/angular.json (2084 bytes)
CREATE angular-aws-waf-captcha/package.json (970 bytes)
CREATE angular-aws-waf-captcha/tsconfig.json (957 bytes)
CREATE angular-aws-waf-captcha/tsconfig.app.json (429 bytes)
CREATE angular-aws-waf-captcha/tsconfig.spec.json (441 bytes)
CREATE angular-aws-waf-captcha/.vscode/extensions.json (130 bytes)
CREATE angular-aws-waf-captcha/.vscode/launch.json (470 bytes)
CREATE angular-aws-waf-captcha/.vscode/tasks.json (978 bytes)
CREATE angular-aws-waf-captcha/src/main.ts (222 bytes)
CREATE angular-aws-waf-captcha/src/index.html (306 bytes)
CREATE angular-aws-waf-captcha/src/styles.scss (80 bytes)
CREATE angular-aws-waf-captcha/src/app/app.scss (0 bytes)
CREATE angular-aws-waf-captcha/src/app/app.spec.ts (690 bytes)
CREATE angular-aws-waf-captcha/src/app/app.ts (246 bytes)
CREATE angular-aws-waf-captcha/src/app/app.html (20086 bytes)
CREATE angular-aws-waf-captcha/src/app/app.config.ts (203 bytes)
CREATE angular-aws-waf-captcha/public/favicon.ico (15086 bytes)
 Packages installed successfully.
    Successfully initialized git.
Enter fullscreen mode Exit fullscreen mode

2. Now we will install and configure the Bootstrap CSS framework. We will do steps 2 and 3 of the post Adding the Bootstrap CSS framework to an Angular application.

3. Next, we will create configuration files for the environment variables with the command below.

ng generate environments
CREATE src/environments/environment.ts (31 bytes)
CREATE src/environments/environment.development.ts (31 bytes)
UPDATE angular.json (2309 bytes)
Enter fullscreen mode Exit fullscreen mode

4. Then, we will configure the variable aws.waf.url with the URL of the JavaScript file containing the AWS WAF integration code and the variable aws.waf.apiKey with the API key that was created in AWS WAF in the src/environments/environment.ts and src/environments/environment.development.ts files as below.

  aws: {
    waf: {
      url: 'https://a162a8302aaa.edge.captcha-sdk.awswaf.com/a162a8302aaa/jsapi.js',
      apiKey: 'QprVjPcLgWgjYBGZoci9OMw9CFJSZZtr2gHt7McsehfL1+Hi+6Rp5y99a0p3vmdsq5Wkat06xfZSTc6dfjvR5w9COBfYhcsXvdRPAGSd9Zxfx6W2QfDsDc2IdiQImVfAl35Uw3tBYd31B3rVlT9q4pEcipVFo29NcqRjYneV7peX2Q+vvd4ttjX0QuM3d+csxtCjaHYSquk6nySEun5QTnbUsq0TE2gliQRFYgHFX9vXSWrkkAXHwWtaxr86kzIeIPoesRAC3JB7kwyK6l4sYoo6w7fTSougEwpjJHGIo8LHdjlxmmNpE2umf1z1go3Ixjm/ujc919tn2FCuGbnW4OEXVWotx3qjf+FPkFbght+ccXsXsL2eHoPgj0sHKaeK0fYpGlJnpwDp+ep64+UVm46Y7Udr7RVLjCnngBcgTRnmA20uy+agfhRnBJk6Y34OgJQJnWuoYXCoVETlFus4ATJ69dny8/6GxUUObjcU6gnfpyR5vkaqmKwSluu6i/x90o9pm1/TTFeh4iuSGylrMySzOe4PsxqMOYR9ow9hnrm7fXz+yE2GoQUJjLWpOUfcmcFmOonjslxIxwDjafWBPACec3JBWGYjAF0H+98Bg6vPly9wlxJwiz6eiMjULPfb1lM7rr6crZ1VaZ964pw21FZSrOdAMknmGSZvmKGAzeU=_1_1',
    },
  },
Enter fullscreen mode Exit fullscreen mode

5. After configure the variables, we will remove the content of the App class from the src/app/app.ts file, create the loadScript and renderCaptcha methods and implement the ngAfterViewInit method of the AfterViewInit class that it will execute the loadScript method as below.

export class App implements AfterViewInit {

  captchaRef = viewChild>('captcha');
  messageSuccess = model('');
  messageError = model('');

  constructor() {
  }

  ngAfterViewInit(): void {
    this.loadScript();
  }

  private loadScript(): void {
    if (document.getElementById('awsWafScript')) {
      return;
    }

    const script = document.createElement('script');
    script.id = 'awsWafScript';
    script.async = false;
    script.defer = true;
    script.src = environment.aws.waf.url;
    script.onload = () => {
      this.renderCaptcha();
    };
    document.head.appendChild(script);
  }

  private renderCaptcha(): void {
    const captchaElementRef = this.captchaRef();

    if (window.AwsWafCaptcha && captchaElementRef) {
      window.AwsWafCaptcha.renderCaptcha(captchaElementRef.nativeElement, {
        apiKey: environment.aws.waf.apiKey,
        onSuccess: (token: string) => {
          this.messageSuccess.set(`Captcha successfully validated! Token: ${token}`);
          this.messageError.set('');
        },
        onError: (error: any) => {
          this.messageError.set(`Error validating captcha: ${error}`);
          this.messageSuccess.set('');
        },
      });
    }
  }

}
Enter fullscreen mode Exit fullscreen mode

6. Now we will remove the content from the src/app/app.html file and add the div tag with the captcha reference variable as below.

<div class="container-fluid py-3">
  <h1>Angular AWS WAF Captcha</h1>

  <div class="row mt-3">
    <div class="col-sm-12">
      <div #captcha></div>
    </div>
  </div>
  <div class="row mt-3">
    <div class="col-sm-12">
      <p class="text-center text-success">{{ messageSuccess() }}</p>
      <p class="text-center text-danger">{{ messageError() }}</p>
    </div>
  </div>
</div>
Enter fullscreen mode Exit fullscreen mode

7. Next, we will run the application with the command below.

npm run start

> angular-aws-waf-captcha@1.0.0 start
> ng serve

Initial chunk files | Names         |  Raw size
styles.css          | styles        | 377.03 kB | 
main.js             | main          |   6.10 kB | 

                    | Initial total | 383.13 kB

Application bundle generation complete. [2.375 seconds] - 2026-01-17T18:13:56.184Z

Watch mode enabled. Watching for file changes...
NOTE: Raw file sizes do not reflect development server per-request transformations.
    Local:   http://localhost:4200/
    press h + enter to show help
Enter fullscreen mode Exit fullscreen mode

8. Then, we will access the URL http://localhost:4200/ and check if the application is working.

Amazon WAF - Angular application


Application running locally.

Amazon WAF - Angular application with validation error


Application running locally with captcha validation error.

Amazon WAF - Angular application with validation success


The application is running on GitHub Pages (https://rodrigokamada.github.io/angular-aws-waf-captcha/) with captcha validation success.

9. Ready! The Angular application was created and integrated with the AWS WAF CAPTCHA challenge.

The application repository is available at https://github.com/rodrigokamada/angular-aws-waf-captcha.

Conclusion

Summarizing what was covered in this article:

  • We created the API key and configured the domain where the captcha will work in AWS WAF.
  • We created an Angular application and added the captcha code.

You can use this article to create web applications with bot protection using the AWS WAF captcha challenge.

Thank you for reading and I hope you enjoyed the article!

This tutorial was posted on my blog in portuguese.

To stay updated whenever I post new articles, follow me on Twitter and LinkedIn.

Top comments (0)