AWS Builder Center
The Front Door: Securing API Gateway with WAF and Custom Authorizers

The Front Door: Securing API Gateway with WAF and Custom Authorizers

The capstone of the Shift-Left serverless series. Learn how to protect your public APIs from malicious traffic using AWS WAF, and enforce zero-trust authentication using JSON Web Tokens (JWT) and Lambda Authorizers.

Series: The Shift-Left Serverless Pipeline. (5 articles)

  1. …
  2. 5
    The Front Door: Securing API Gateway with WAF and Custom Authorizers This article
Backend Developer aiming for DevSecOps
Welcome to the fifth and final capstone article of our "Shift-Left Serverless Pipeline" series!
If you have followed along, we have built a truly impressive DevSecOps architecture:
  1. Pipeline Identity: We eliminated static keys using GitHub OIDC.
  1. Code Security: We integrated SonarCloud (SAST) and OWASP (SCA) to block vulnerabilities during the build phase.
  1. Runtime Security: We restricted our AWS Lambda functions using strict Least-Privilege IAM roles.
  1. Observability: We illuminated our system with AWS X-Ray and CloudWatch Alarms.
However, there is one glaring vulnerability left. Our pipeline is a fortress, our code is clean, and our runtime is restricted, but our Amazon API Gateway is sitting completely open on the public internet.
Anyone with the URL can send unlimited requests, potentially executing a Denial of Service (DoS) attack, attempting SQL injections, or spamming our database.
In this capstone article, we will secure "The Front Door." We will implement Edge Protection using a Web Application Firewall (AWS WAF) and enforce Zero-Trust Authentication using a Custom Lambda Authorizer.



1. The Threat Landscape at the Edge

When you expose a REST API to the internet, it is immediately subjected to automated bot traffic and malicious probes.
Even if your Lambda function only has IAM permissions to write to a specific DynamoDB table, a malicious actor can still flood your API Gateway with millions of requests. Because serverless architectures scale automatically, this flood will trigger millions of Lambda executions. This is known as a Denial of Wallet (DoW) attack, where the attacker's goal is to inflate your AWS monthly bill astronomically.
To mitigate this, we cannot rely on application logic alone. We must stop the traffic before it ever reaches our Lambda functions.
Image showing a shield protecting the normal workload flow




2. Shielding the Edge: AWS WAF

AWS WAF (Web Application Firewall) is a security service that lets you monitor HTTP/HTTPS requests forwarded to your Amazon API Gateway, Amazon CloudFront, or Application Load Balancer.
Think of WAF as a highly intelligent bouncer at the door of your application. You give the bouncer a list of rules (a Web Access Control List, or Web ACL), and it inspects every incoming request in milliseconds.

Essential WAF Rules for Serverless

Instead of writing complex rules from scratch, AWS provides Managed Rule Groups, pre-configured rules updated automatically by AWS security research teams. For a standard API, you should enable:
  1. Core Rule Set: Blocks common vulnerabilities defined by the OWASP Top 10, such as bad IP reputations and malformed requests.
  1. SQL Injection (SQLi) Rule: Blocks requests containing malicious SQL code in the query strings or body.
  1. Rate Limiting: Automatically blocks an IP address if it sends too many requests within a 5-minute window, effectively neutralizing DoS and brute-force attacks.
By defining AWS WAF in our Infrastructure as Code (IaC), we shift edge security to the left, ensuring our API is never deployed without its shield.



3. Zero-Trust Authentication: Lambda Authorizers

AWS WAF stops malicious traffic, but how do we identify legitimate traffic? How do we ensure that the user calling our  POST /orders  endpoint is actually logged into our application?
We need an Authentication Layer.
While you can use Amazon Cognito natively with API Gateway, a highly flexible and widely used corporate standard is the Lambda Custom Authorizer validating JSON Web Tokens (JWT).

How a Lambda Authorizer Works

  1. A client application (like a React frontend) authenticates a user and receives a JWT.
  1. The client sends a request to your API Gateway, placing the JWT in the  Authorization  header.
  1. Before API Gateway routes the request to your main application logic, it triggers a special, separate Lambda function, the Authorizer.
  1. The Authorizer verifies the token's cryptographic signature, checks its expiration date, and inspects its claims.
  1. If valid, the Authorizer returns an IAM policy granting the request access to the main API endpoint. If invalid, API Gateway immediately returns a  401 Unauthorized  without ever touching your core business logic.
Representation of a request being authorized or being denied




4. Defining the Front Door in AWS SAM

The beauty of DevSecOps is that all of these security measures are defined in code and reviewed in our GitHub PRs before deployment.
Here is how we integrate a Custom Authorizer and link a WAF WebACL to our API Gateway using an AWS SAM  template.yaml .
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: API Gateway with Lambda Authorizer and AWS WAF

Resources:

# 1. The Custom Lambda Authorizer Function
MyApiAuthorizerFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: src/authorizer/
Handler: com.example.auth.Authorizer::handleRequest
Runtime: java21
MemorySize: 512

# 2. The API Gateway (Configured with the Authorizer)
SecureApiGateway:
Type: AWS::Serverless::Api
Properties:
StageName: Prod
Auth:
DefaultAuthorizer: JwtAuthorizer
Authorizers:
JwtAuthorizer:
FunctionArn: !GetAtt MyApiAuthorizerFunction.Arn
Identity:
Header: Authorization # Expects the JWT here
ValidationExpression: "^Bearer [-0-9a-zA-Z\\._]*$"

# 3. The Core Business Logic (Protected by the API)
ProcessOrderFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: src/app/
Handler: com.example.app.OrderHandler::handleRequest
Runtime: java21
Events:
ApiEvent:
Type: Api
Properties:
Path: /orders
Method: post
RestApiId: !Ref SecureApiGateway

# 4. AWS WAF Web ACL (The Edge Shield)
ApiWafWebAcl:
Type: AWS::WAFv2::WebACL
Properties:
Name: SecureApiWebAcl
Scope: REGIONAL # Because API Gateway is regional
DefaultAction:
Allow: {}
VisibilityConfig:
SampledRequestsEnabled: true
CloudWatchMetricsEnabled: true
MetricName: SecureApiWafMetrics
Rules:
# Enable AWS Managed Core Rule Set (OWASP Protection)
- Name: AWSManagedRulesCommonRuleSet
Priority: 1
Statement:
ManagedRuleGroupStatement:
VendorName: AWS
Name: AWSManagedRulesCommonRuleSet
OverrideAction:
None: {}
VisibilityConfig:
SampledRequestsEnabled: true
CloudWatchMetricsEnabled: true
MetricName: AWSCommonRulesMetric

# 5. Attach WAF to the API Gateway Stage
ApiWafAssociation:
Type: AWS::WAFv2::WebACLAssociation
Properties:
ResourceArn: !Sub "arn:aws:apigateway:${AWS::Region}::/restapis/${SecureApiGateway}/stages/Prod"
WebACLArn: !GetAtt ApiWafWebAcl.Arn

Breaking Down the Code

  • Security by Default: By placing  DefaultAuthorizer: JwtAuthorizer  at the API level, every single endpoint we create in this API Gateway is protected automatically. Developers cannot accidentally expose an endpoint.
  • WAF Association: The  WebACLAssociation  resource binds our WAF directly to the API Gateway  Prod  stage. If a request trips the Core Rule Set, the WAF returns a  403 Forbidden  instantly.



5. The Complete DevSecOps Architecture

With this final piece in place, we have engineered a true, enterprise-grade serverless architecture. Let's trace the journey of a single line of code and a single HTTP request:
The Developer Journey (The Pipeline):
  1. You commit code to GitHub.
  1. GitHub Actions runs Gradle, triggering SonarCloud (SAST) and OWASP (SCA) to ensure the code is clean and dependencies are secure.
  1. Actions fetches temporary deployment credentials securely via OIDC.
  1. AWS SAM deploys the infrastructure.
The User Journey (The Runtime):
  1. A user sends a request to your API.
  1. AWS WAF inspects the payload, ensuring it is not a bot, a DoS attack, or a SQL injection.
  1. API Gateway intercepts the request and passes the JWT to the Lambda Authorizer.
  1. The Authorizer verifies the user's identity cryptographically.
  1. Finally, the main Lambda function executes the business logic, constrained safely by its Least-Privilege IAM role, while AWS X-Ray and CloudWatch log the entire traced transaction.

Conclusion

DevSecOps is the philosophy that security is not an afterthought, a separate team, or a final checkbox. It is woven into the very fabric of how we write code, design pipelines, and architect cloud environments. By shifting security left, we build robust systems that protect our companies and our users by design.
Thank you for joining me on this 5-part architectural journey on the AWS Builder Center!
Let’s discuss: Have you ever implemented a Custom Authorizer or faced challenges configuring AWS WAF? Share your experiences, or let me know what cloud engineering topics you would like to see in my next series!

Series: The Shift-Left Serverless Pipeline. (5 articles)

  1. …
  2. 5
    The Front Door: Securing API Gateway with WAF and Custom Authorizers This article
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article