Sunday, August 17, 2025

API Gateway | Security Overview & Hands-On.

Here’s twtech deep-dive into API Gateway security (focusing on AWS API Gateway).

API Gateway acts as the front door to backend services, making it a critical security enforcement point.

Security includes:

  •  Identity & access management,
  • Network controls,
  • Traffic protection,
  • Monitoring.

1. Authentication & Authorization

·        IAM-based access

o   Use IAM policies & roles to control which AWS principals (users, roles, services) can call your API.

o   Common for service-to-service calls.

·        Cognito User Pools / JWT Authorization

o   Delegates authentication to Amazon Cognito or external IdPs (OIDC, SAML).

o   Clients present JWT tokens, verified by API Gateway.

·        Lambda Authorizers (Custom Auth)

o   Custom logic (e.g., verify API keys, call external IdP, check entitlements).

o   Returns an IAM policy to allow/deny requests.

·        Resource Policies

o   Define which accounts, VPCs, or CIDR ranges can invoke an API (IP whitelisting, VPC restriction).

o   Essential for private endpoints.

·        API Keys + Usage Plans

o   Simple way to identify clients (not strong security, more for rate-limiting/quotas).

o   Best combined with stronger auth (JWT/IAM).

2. Network & Endpoint Security

·        Endpoint Types

o   Edge-optimized – Public internet, global CloudFront distribution.

o   Regional – Public internet, regional only.

o   Private – Accessible only inside a VPC via PrivateLink.

·        VPC Links

o   Securely connect API Gateway to private resources in VPC (e.g., ECS, ALB, NLB).

·        Resource Policies for Network Controls

o   Restrict access to VPCs, IP ranges, or specific AWS accounts.

·        WAF Integration

o   Attach AWS WAF to block SQLi, XSS, bad bots, or enforce geo restrictions.

3. Data Protection

·        TLS Enforcement (HTTPS only)

o   API Gateway enforces HTTPS; TLS 1.2+ recommended.

o   Can enforce strong cipher suites.

·        Custom Domain Names with ACM Certificates

o   Bind custom TLS certs for branding and stronger trust.

·        Payload Encryption

o   Encrypt requests/responses in transit (TLS...Transport Layer Security)

o   Encrypt data at rest (logs, cached responses).

·        Request/Response Validation

o   Schema validation (JSON/XML) to prevent injection attacks and malformed data.

4. Threat Protection & Rate Control

·        Throttling

o   Global (per account) and per-API stage/method throttles.

o   Protects backend from flooding.

·        Usage Plans & Quotas

o   Per-client throttles and quotas with API keys.

·        WAF Rules

o   Block OWASP Top 10 threats, rate-limiting, bot control.

·        Request/Response Transformation

o   Strip sensitive data before forwarding or logging.

5. Monitoring & Logging

·        CloudWatch Logs & Metrics

o   Capture request/response metadata, latencies, errors.

o   Detect anomalies & suspicious traffic.

·        Access Logging

o   Log client IPs, identities, request paths.

·        AWS X-Ray

o   End-to-end tracing for performance/security visibility.

·        GuardDuty & CloudTrail

o   Detect malicious activity and unauthorized API calls.

6. Best Practices

Always require strong authentication (JWT/IAM over API Keys alone).
Use least-privilege IAM roles & resource policies.
Prefer private endpoints + VPC Link for sensitive APIs.
Enable WAF + throttling to protect from DDoS & abuse.
Enforce schema validation to prevent injection.
Rotate API keys & secrets regularly.
Continuously monitor logs & metrics.

A sketch of AWS Security Reference Architecture for API Gateway in text form.

AWS API Gateway Security Reference Architecture (Text Diagram)

 

                ┌──────────────────────────────┐
                │                              Clients                                   │
                │               (Web, Mobile, Services)                      │
                └───────────────┬──────────────┘
                                                         │ HTTPS (TLS/ACM)
                                                        ▼
                      ┌───────────────────┐
                      │  AWS WAF + Shield               │
                      │  (Threat Protection)               │
                      └───────────┬───────┘
                                                     │
                                                    ▼
                        ┌───────────────────┐
                        │             API Gateway      
                        │          (Central Control)          │
                        └──────────┬────────┘
        ┌─────────────────────────────────────────────────┐
                                │                                       │                                           │
                               ▼                                      ▼                                         ▼
 ┌───────────────┐        ┌───────────────┐         ┌────────────────┐
 Authentication             │        │ Data Protection           │        │ Threat Control
 │ & Authorization          │     │  - TLS Enforce       │     │ - Throttling           │
 │ - IAM Policies       │     │  - Schema Val.     │     │ - Usage Plans         │
 │ - Cognito/JWT             │        │                                       │        │ - Quotas                          │
 │ - Lambda Auth            │        └───────────────┘        └────────────────┘
 │ - API Keys                    │
 └───────────────┘
                                                             │
                                                            ▼
                ┌───────────────────────────────────┐
                │          VPC / PrivateLink                                                  │
         │   (Private API, VPC Link to ALB,                   │
                │    ECS, Lambda, RDS, etc.)                                            │
                └───────────────────────────────────┘
                                                            │
                                                           ▼
                      ┌──────────────────────┐
                      │     Backend Apps                           │
                      │  (ECS, Lambda, etc.)                     │
                      └──────────────────────┘
                                                            │
                                                           ▼
                ┌───────────────────────────────────┐
         │   Monitoring & Logging (Security)                 
                │ - CloudWatch Logs & Metrics                                       │
         │ - CloudTrail (API Activity)                      
                │ - GuardDuty (Threat Detection)                                       │
                │ - X-Ray (Tracing)                                                             │
                └───────────────────────────────────┘

 Key Security Layers

·        Perimeter → WAF + Shield (DDoS, injection protection)

·        Auth → IAM, Cognito, Lambda Authorizers

·        Network → PrivateLink/VPC Link, Resource Policies

·        Data Protection → TLS (ACM), Schema Validation

·        Abuse Protection → Throttling, Usage Plans, Quotas

·        Monitoring → CloudWatch, CloudTrail, GuardDuty, X-Ray

twtech-insights:

The creation of a perfect, interactive AWS architecture diagram is not possible in text. However, a description of the architecture and the connections between the services can be provided to show how authentication, WAF, private links, and logging integrate with AWS API Gateway.

Here is a breakdown of the components and their connections:

Core components

·        Clients: Applications or users making requests to the API.

·        AWS API Gateway: Acts as the entry point for API requests, handling routing, authorization, and other functions before forwarding requests to backend services.

·        Backend Services: Actual logic of the API, often implemented using AWS Lambda functions, Amazon EC2 instances, or other services.

Security layers and their connections

1. Authentication and authorization

·        Mechanism: AWS API Gateway supports various authentication and authorization methods, including IAM, Amazon Cognito User Pools, and custom Lambda Authorizers.

·        Connection to API Gateway:

o   Lambda Authorizers: API Gateway invokes a Lambda function to authenticate requests before they reach the backend service.

o   Amazon Cognito: Client applications obtain tokens from Amazon Cognito, which are then validated by API Gateway.

o   IAM: Requests are signed with IAM credentials, and API Gateway validates them against IAM policies.

2. Web Application Firewall (WAF)

·        Purpose: Protects against common web exploits and unwanted bot traffic.

·        Connection to API Gateway:

o   Associate a WAF Web ACL (Web Access Control List) with your API Gateway stage.

o   Requests are inspected by WAF rules before reaching the API Gateway.

3. Private links

·        Purpose: Allow private connectivity between VPCs and services, preventing exposure to the public internet.

·        Connection to API Gateway:

o   For private APIs, API Gateway integrates with AWS PrivateLink to create interface VPC endpoints.

o   Requests to private APIs go through these endpoints, ensuring traffic remains within the AWS network.

o   VPC endpoint policies further restrict access to specific private APIs via the endpoint.

o   For integrating with backend services in other VPCs, twtech might use VPC links and private integrations with API Gateway.

4. Logging and monitoring

·        Service: Amazon CloudWatch Logs for storing and analyzing API Gateway logs.

·        Connection to API Gateway:

o   Enable logging in API Gateway at the stage level.

o   Configure execution logs to capture requests, responses, errors, etc.

o   Configure access logs for tracking who accessed the API and how.

o   API Gateway needs an IAM role with permissions to write to CloudWatch Logs.

Explanation:

  •        Clients initiate requests to the API Gateway.
  •         WAF inspects and filters requests before they reach the API Gateway.
  •        Authentication and Authorization happen next, verifying the client's identity and permissions.
  •         For private APIs, the requests then route through the VPC Endpoints (powered by AWS PrivateLink) to reach the backend services in your VPC, keeping traffic off the public internet.
  •        Finally, CloudWatch Logs collect logs from the API Gateway (and potentially other services) for monitoring, troubleshooting, and auditing.

The above diagram highlights how each security layer plays a crucial role in safeguarding the API Gateway and the backend services it protects. 

Remember to apply the principles of least privilege(PoLP) and regularly review and audit the security configurations.

Project: Hands-On

How twtech Builds API Gateway for its Resources:

Search for aws service: API Gateway


Some vital details:

Get started

Twtech can create a new API to begin exploring API Gateway. it can also import an external definition file into API Gateway.

Create an API

Choose an API type: REST API

Develop a REST API where you gain complete control over the request and response along with API management capabilities.

Works with the following:

Lambda, HTTP, AWS Services

Create REST API

Assign a name: twtech-API

API endpoint type

Regional APIs are deployed in the current AWS Region. Edge-optimized APIs route requests to the nearest CloudFront Point of Presence. Private APIs are only accessible from VPCs.

How twtech creates methods in the API

Create method

Method details

Method type

First, twtech needs to create a lambda function for api: twtech-api-function


# Code:

import json

def lambda_handler(event, context):

    # TODO implement

    return {

        'statusCode': 200,

        'body': json.dumps('Hello from twtech Lambda!')

    }

How twtech Deploys a function:


How twtech tests any function created: twtech-api-fucntion-test


How to save:  Test events


How to see the details of the test function:

Next: twtech integrates the Lambda function into the API Gateway.

Create method: twtech-api-lanbda-method

twtech needs to verify that the lambda function(twtech-api-function) can fetch data from the API Gateway: Lambda function console.

How twtech access and edit the configuration for the function: twtech-api-function 

How twtech access and edit the permissions for the function: twtech-api-function 

Select and view policy:

Policy:

How twtech tests the function of API: 

Successful:

How to find exactly what can be sent to the lambda function from:  API Gateway code

Add: Print event to the code.

 Deploy the code.

Invoke another lambda function by running a test:


View details of the test events: twtech-api-function-test2

How to virify if the events are successfully printed in the:  CloudWatch logs under function Monitoring tab.

View CloudWatch logs:

Click to get indeep analysis (Observability) from:  log streams

How to create new resources for API Gateway methods: Resources

Create resource with name: twtech-resources




Create method : Method details

Method type

Create a function to get for twtech-resources created:  twtech-resource-function-get-API


Edit the code, deploy, test, save verify, monitory:

Deploy the code:

Test the code:

Verify  the details 

Save the tests:


View logs: Cloudwatch

Now the function ARN can be used to complete the creation of the method: twtech-resource-method


How to Test the  get method created for: twtech-resources


How twtech accesss the resoucecs  methods created from the web browser:

First , deploy the API:


Deploy:

How to access the method url from the web browser: chrome

https://fxh4xxx.execute-api.us-east-2.amazonaws.com/dev

https://fxh4a0xxx.execute-api.us-east-2.amazonaws.com/dev/twtech-resources


No comments:

Post a Comment

Mobile Application MyTodoList | Achitecture, Plus User Interface (app UI).

  A deep dive into building a mobile application called MyTodoList …. An end-to-end architecture, design, backend, deployment, and DevOps/...