AWS API Gateway - WebSocket API + EC2 (HTTP & VPC Link & Auth & API Keys & Lambda Authorizer)

4 min read 1 year ago
Published on Aug 07, 2024 This response is partially generated with the help of AI. It may contain inaccuracies.

Table of Contents

Introduction

This tutorial will guide you through the process of creating a WebSocket API using AWS API Gateway and integrating it with an EC2 instance. You'll learn to handle real-time messaging, manage connections, and implement security features like API keys and Lambda authorizers. This setup is ideal for building real-time applications, such as chat services or live notifications.

Step 1: Create a WebSocket API in API Gateway

  • Sign in to the AWS Management Console.
  • Navigate to the API Gateway service.
  • Choose "Create API" and select "WebSocket API."
  • Set the API name and provide a route selection expression (e.g., $request.body.action).
  • Click "Create API."

Step 2: Create Public HTTP Backend Integration

  • In your WebSocket API, navigate to the "Routes" section.
  • Define routes for connection management:
    • $connect: for new connections
    • $disconnect: for closing connections
    • sendmessage: for sending messages
  • Choose "Integrations" and select "HTTP" to integrate with your backend.

Step 3: Use Stage Variables

  • Go to the "Stage" section of your API.
  • Add stage variables to manage different environments (e.g., dev, prod).
  • Use these variables in your integration responses and routes.

Step 4: Pass Connection ID in the Header

  • Modify the integration request for the sendmessage route.
  • Add the connection ID in the HTTP headers to route messages to the correct client.

Step 5: Create DynamoDB Database

  • Open the DynamoDB service in the AWS console.
  • Create a new table to store connection IDs.
  • Use "connectionId" as the primary key.

Step 6: Configure $connect Route to Save Connection ID to DynamoDB

  • In your integration setup for the $connect route, implement a Lambda function.
  • This function should save the connection ID to your DynamoDB table:
    const AWS = require('aws-sdk');
    const dynamoDB = new AWS.DynamoDB.DocumentClient();
    
    exports.handler = async (event) => {
        const connectionId = event.requestContext.connectionId;
        await dynamoDB.put({
            TableName: 'YourTableName',
            Item: {
                connectionId: connectionId,
            },
        }).promise();
    };
    

Step 7: Configure $disconnect Route to Delete Connection ID from DynamoDB

  • Like the $connect route, set up a Lambda function for $disconnect.
  • Ensure it removes the connection ID from the DynamoDB table.

Step 8: Configure sendmessage Route to Push Messages

  • Implement a Lambda function for the sendmessage route.
  • Use the connection ID stored in DynamoDB to push messages to connected clients.

Step 9: Create VPC Link Private Integration

  • Navigate to "VPC Links" in API Gateway.
  • Create a new VPC link to connect your API Gateway to your EC2 instance.

Step 10: Create Custom Domain for WebSocket API

  • In the API Gateway, go to "Custom Domain Names."
  • Add a new domain name and associate it with your WebSocket API.
  • Configure SSL certificates if necessary.

Step 11: Implement Request Validation

  • Set request validation on routes to ensure incoming requests meet defined schemas.
  • This helps prevent malformed requests from reaching your backend.

Step 12: Throttle API Requests

  • Set up throttling in the usage plan section.
  • Specify rate limits to control the number of requests users can make.

Step 13: Access Control with Lambda Authorizer

  • Create a Lambda authorizer to manage access to your WebSocket API.
  • Implement logic to check user permissions and return an IAM policy.

Step 14: Control Access and Quotas with Usage Plan and API Keys

  • In the API Gateway, create a usage plan that includes API keys.
  • Associate the usage plan with your API to manage access and quotas effectively.

Conclusion

You've now set up a WebSocket API using AWS API Gateway, integrated it with an EC2 instance, and implemented key features like connection management, request validation, and access control. This architecture is perfect for building responsive real-time applications. For further exploration, consider implementing additional features like message broadcasting or user authentication.