Select your cookie preferences

We use cookies and similar tools to enhance your experience, provide our services, deliver relevant advertising, and make improvements. Approved third parties also use these tools to help us deliver advertising and provide certain site features.

AWS WAF attached to Amazon API Gateway REST API

Created with SnapAWS WAFAmazon API GatewayAWS Lambda

Creates an Amazon API Gateway with a WebACL attached to control access. This WebACL limits the requests to certain countries.

This sample project demonstrates how to use AWS WAF to add extra security to an Amazon API Gateway REST API. In this example, only requests from the US will be accepted. All others will be rejected with a 403. To add another country, add the country code to the 'CountryCode' array starting on line 32.

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: Serverless patterns - AWS WAF to Amazon API Gateway REST (uksb-1tthgi812) (tag:waf-apigw-rest)

Resources:
  # AWS WAF Access Control List limits each IP to 100 requestes per second
  MyWAFACL:
    Type: AWS::WAFv2::WebACL
    Properties:
      CustomResponseBodies: # Define a response from WAF
        CountryNotValid:
          Content: Country not allowed
          ContentType: TEXT_PLAIN
      DefaultAction:
        Block: 
          CustomResponse: # Choose a defined template to respond when blocked
            ResponseCode: "403"
            CustomResponseBodyKey: CountryNotValid
      Description: Application WAF
      Scope: REGIONAL
      VisibilityConfig:
        CloudWatchMetricsEnabled: true
        MetricName: AppRules
        SampledRequestsEnabled: true
      Rules:
        - Action:
            Allow: {} # Allow if conditions are met
          Name: AllowCountryList
          Priority: 0
          Statement:
            GeoMatchStatement:
              CountryCodes: # Requests from following countries are allowed (Add your country code to test)
                - US
          VisibilityConfig:
            CloudWatchMetricsEnabled: true
            MetricName: AllowCountryList
            SampledRequestsEnabled: true
  
  # Amazon API gateway REST API
  MyApi: 
    Type: AWS::Serverless::Api 
    Properties: 
      StageName: Prod
      EndpointConfiguration: REGIONAL
      TracingEnabled: true

  # Associate the WebACL with the API gateway
  MyWAFAssociation:
    Type: AWS::WAFv2::WebACLAssociation
    Properties: 
      ResourceArn: !Sub arn:aws:apigateway:${AWS::Region}::/restapis/${MyApi}/stages/${MyApi.Stage}
      WebACLArn: !GetAtt MyWAFACL.Arn

# Lambda function as an example micro-service behind the API Gateway REST endpoint
  MyLambdaFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: src/
      Handler: app.lambda_handler
      Runtime: python3.9
      Events:
        RootGet:
          Type: Api
          Properties:
            Path: /
            Method: get
            RestApiId: !Ref MyApi

Outputs:
  # API endpoint for testing
  ApiEndpoint:
    Description: "API endpoint URL"
    Value: !Sub https://${MyApi}.execute-api.${AWS::Region}.amazonaws.com/Prod

< Back to all patterns


GitHub icon Visit the GitHub repo for this pattern.

Download

git clone https://github.com/aws-samples/serverless-patterns/ cd serverless-patterns/waf-apigw-rest

Deploy

sam deploy


Testing

See the GitHub repo for detailed testing instructions.

Cleanup

Delete the stack: sam delete.

Additional resources

Eric Johnson

Presented by Eric Johnson

Eric Johnson is a Principal Developer Advocate for Serverless Applications at Amazon Web Services and is based in Northern Colorado. Eric is a fanatic about serverless and enjoys helping developers understand how serverless technologies introduces a major paradigm shift in how they approach building and running applications at massive scale with minimal administration overhead. Prior to this, Eric has worked as a developer, solutions architect and AWS Evangelist for an AWS partner company.

Follow on LinkedIn