Sunday, August 17, 2025

API Gateway Security | Overview & Hands-On.

API Gateway Security - Overview & Hands-On.

Scope:

  • Intro,
  • Authentication & Authorization,
  • Network & Endpoint Security,
  • Data Protection,
  • Threat Protection & Rate Control,
  • Monitoring & Logging,
  • Best Practices,
  • Security Reference Architecture for API Gateway,
  • Insights,
  • Project: Hands-On.

Intro:

  • 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

    •    Use IAM policies & roles to control which AWS principals (users, roles, services) can call your API.
    •    Common for service-to-service calls.

        Cognito User Pools / JWT Authorization

    •    Delegates authentication to Amazon Cognito or external IdPs (OIDC, SAML).
    •    Clients present JWT tokens, verified by API Gateway.

        Lambda Authorizers (Custom Auth)

    •    Custom logic (e.g., verify API keys, call external IdP, check entitlements).
    •    Returns an IAM policy to allow/deny requests.

        Resource Policies

    •    Define which accounts, VPCs, or CIDR ranges can invoke an API (IP whitelisting, VPC restriction).
    •    Essential for private endpoints.

        API Keys + Usage Plans

    •    Simple way to identify clients (not strong security, more for rate-limiting/quotas).
    •    Best combined with stronger auth (JWT/IAM).

2. Network & Endpoint Security

        Endpoint Types

    •    Edge-optimized – Public internet, global CloudFront distribution.
    •    Regional – Public internet, regional only.
    •    Private – Accessible only inside a VPC via PrivateLink.

        VPC Links

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

        Resource Policies for Network Controls

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

        WAF Integration

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

3. Data Protection

        TLS Enforcement (HTTPS only)

    •    API Gateway enforces HTTPS; TLS 1.2+ recommended.
    •    Can enforce strong cipher suites.

        Custom Domain Names with ACM Certificates

    •    Bind custom TLS certs for branding and stronger trust.

        Payload Encryption

    •    Encrypt requests/responses in transit (TLS...Transport Layer Security)
    •    Encrypt data at rest (logs, cached responses).

        Request/Response Validation

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

4. Threat Protection & Rate Control

        Throttling

    •    Global (per account) and per-API stage/method throttles.
    •    Protects backend from flooding.

        Usage Plans & Quotas

    •    Per-client throttles and quotas with API keys.

        WAF Rules

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

        Request/Response Transformation

    •    Strip sensitive data before forwarding or logging.

5. Monitoring & Logging

        CloudWatch Logs & Metrics

    •    Capture request/response metadata, latencies, errors.
    •    Detect anomalies & suspicious traffic.

        Access Logging

    •    Log client IPs, identities, request paths.

        AWS X-Ray

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

        GuardDuty & CloudTrail

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

 Security Reference Architecture for API Gateway.

 Key Security Layers

  •         Perimeter WAF + Shield (DDoS, injection protection)
  •         AuthIAM, 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:

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

  •    Associate a WAF Web ACL (Web Access Control List) with your API Gateway stage.
  •    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:

  •    For private APIs, API Gateway integrates with AWS PrivateLink to create interface VPC endpoints.
  •    Requests to private APIs go through these endpoints, ensuring traffic remains within the AWS network.
  •    VPC endpoint policies further restrict access to specific private APIs via the endpoint.
  •    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:

  •    Enable logging in API Gateway at the stage level.
  •    Configure execution logs to capture requests, responses, errors, etc.
  •    Configure access logs for tracking who accessed the API and how.
  •    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.

NB:

  • 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 twtech gains 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


  • Create funtion: twtechApiGetFunction


# Deploy code:

import json
def lambda_handler(event, context):
    # TODO implement
    return {
        'statusCode': 200,
        'body': json.dumps('Hello from twtech Lambda Team')
    }

  • Test Deployment and save: twtechApiGetFunctionTest


  • How twtech tests any function created: Test the Events
  • How to see the details of the test function: Details of test Events


  • Integrate the Lambda Function(twtechApiFunctionGet) into the API Gateway(twtech-Rest-API):
  • Use the Function ARN to integrate with the API Gateway

arn:aws:lambda:us-east-2:98
xxxxxxxxxxx:function:twtechApiFunctionGet



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

  • Configure (select) the Method type and associate (integrate) the Function ARN to: API Method. 



  • Create method: twtechApiLambdaMethod

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

  • How twtech accesses and edit the configuration for the function: twtech-api-function 

  • How twtech accesses 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.


# twtech-print-code
import json
def lambda_handler(event, context):
    print(event)
    # TODO implement
    return {
        'statusCode': 200,
        'body': json.dumps('Hello from twtech Lambda Team')
    }

  • Again: twtech needs to Reploy the code and test the Lambda function.

  • Again: Test the Lambda function.


  • Alternative way to test the: code in Lambda Function.

  • Invoke another lambda function by running a test:


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

  • Again , twtech needs to test the created: API Gateway 


  • twtech needs to refresh the page and verify that the Lambda function is  successfully integrated to: API Gateway

  • twtech needs to verify that the events can successfully be printed in the: CloudWatch logs by going to Lambda function Monitoring tab/View CloudWatch Logs.

  • 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



  • Again, Create method in twtech-resources. 
  • Make sureLambda proxy integration is: Enabled.
  • Method details: Method type


  • Again, twtech needs to create a function to get for twtech-resources created:  twtech-resource-function-get-API


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

# twtech-resources-Code
import json
def lambda_handler(event, context):
    # TODO implement
    return {
        'statusCode': 200,
        'body': json.dumps('Hello from twtech Lambda Resource Team ')
    }

# Deploy the code:

  • Deploy the code:

  • Test and save the codetwtechApiGetResources

  • Verify  the details 

  • Save the tests:


  • Again, twtech needs to integrate the function with the created resource in API Gateway : twtechApiGetResources


NB:

  • How twtech eventually View logs: Cloudwatch Logs (enable Lambda proxy integration)
  • 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 accessses the methods created from the web browser:
  • First twtech needs to: Deploy the API


  • Deploy the API in : twtech-dev-env

  • Deploy:


  • How to get API Stages created:

  • How twtech accesses the method url from the web browser: chrome

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

https://fa7evtxxx.execute-api.us-east-2.amazonaws.com/twtech-dev-env




No comments:

Post a Comment

Amazon EventBridge | Overview.

Amazon EventBridge - Overview. Scope: Intro, Core Concepts, Key Benefits, Link to official documentation, Insights. Intro: Amazon EventBridg...