|
| 1 | +# AWS API Gateway Websocket API to AWS Lambda with authorization and mapping template |
| 2 | + |
| 3 | +This pattern will create an AWS API Gateway Websocket API protected by a Lambda authorizer. The websocket is integrated with a Lambda function through a mapping template that passes the main informations of the request. |
| 4 | + |
| 5 | +Learn more about this pattern at Serverless Land Patterns: https://serverlessland.com/patterns/apigw-websocket-mapping-template-authorizer |
| 6 | + |
| 7 | +Important: this application uses various AWS services and there are costs associated with these services after the Free Tier usage - please see the [AWS Pricing page](https://aws.amazon.com/pricing/) for details. You are responsible for any AWS costs incurred. No warranty is implied in this example. |
| 8 | + |
| 9 | +## Requirements |
| 10 | + |
| 11 | +* [Create an AWS account](https://portal.aws.amazon.com/gp/aws/developer/registration/index.html) if you do not already have one and log in. The IAM user that you use must have sufficient permissions to make necessary AWS service calls and manage AWS resources. |
| 12 | +* [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html) installed and configured |
| 13 | +* [Git Installed](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) |
| 14 | +* [AWS Serverless Application Model](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html) (AWS SAM) installed |
| 15 | +* [Install NPM](https://www.npmjs.com/get-npm). |
| 16 | + |
| 17 | +## Deployment Instructions |
| 18 | + |
| 19 | +1. Create a new directory, navigate to that directory in a terminal and clone the GitHub repository: |
| 20 | + ``` |
| 21 | + git clone https://github.com/aws-samples/serverless-patterns |
| 22 | + ``` |
| 23 | +1. Change directory to the pattern directory: |
| 24 | + ``` |
| 25 | + cd apigw-websocket-mapping-template-authorizer |
| 26 | + ``` |
| 27 | +1. From the command line, use AWS SAM to deploy the AWS resources for the pattern as specified in the template.yml file: |
| 28 | + ``` |
| 29 | + sam deploy --guided |
| 30 | + ``` |
| 31 | +1. During the prompts: |
| 32 | + * Enter a stack name |
| 33 | + * Enter the desired AWS Region |
| 34 | + * Allow SAM CLI to create IAM roles with the required permissions. |
| 35 | +
|
| 36 | + Once you have run `sam deploy --guided` mode once and saved arguments to a configuration file (samconfig.toml), you can use `sam deploy` in future to use these defaults. |
| 37 | +
|
| 38 | +1. Note the outputs from the SAM deployment process. These contain the resource names and/or ARNs which are used for testing. |
| 39 | +
|
| 40 | +## How it works |
| 41 | +
|
| 42 | +The architecture uses proxy integration for the `$connect` and `$disconnect` routes, each linked to their respective AWS Lambda functions. The `sendmessage` route uses non-proxy integration with a backend Lambda function, incorporating a mapping template to pass essential data such as the message body and connection ID. |
| 43 | +
|
| 44 | +
|
| 45 | +The Mapping Template used is this one : |
| 46 | +``` |
| 47 | + { |
| 48 | + "requestContext": { |
| 49 | + "routeKey": "$context.routeKey", |
| 50 | + "messageId": "$context.messageId", |
| 51 | + "auth": "$context.authorizer.principalId", |
| 52 | + "token": "$context.authorizer.token", |
| 53 | + "eventType": "$context.eventType", |
| 54 | + "extendedRequestId": "$context.extendedRequestId", |
| 55 | + "requestTime": "$context.requestTime", |
| 56 | + "messageDirection": "$context.messageDirection", |
| 57 | + "stage": "$context.stage", |
| 58 | + "connectedAt": "$context.connectedAt", |
| 59 | + "requestTimeEpoch": "$context.requestTimeEpoch", |
| 60 | + "sourceIp": "$context.identity.sourceIp", |
| 61 | + "requestId": "$context.requestId", |
| 62 | + "domainName": "$context.domainName", |
| 63 | + "connectionId": "$context.connectionId", |
| 64 | + "apiId": "$context.apiId" |
| 65 | + }, |
| 66 | + "body": "$util.escapeJavaScript($input.body)", |
| 67 | + "isBase64Encoded": "$context.isBase64Encoded" |
| 68 | + } |
| 69 | +``` |
| 70 | +The backend Lambda function `SendMessageFunction` operates independently by retrieving the endpoint and DynamoDB table name from environment variables. The API stage name is defined in the Lambda environment variables. To modify the stage name, you can either update the environment variable or extract it from the mapping template in the event sent to Lambda. |
| 71 | +
|
| 72 | +This implementation includes security through a Lambda REQUEST Authorizer. The authorizer function validates the header `token`, granting access only when the token value is "hello". Requests with invalid tokens receive a 401 Unauthorized response. |
| 73 | +
|
| 74 | +All Lambda functions use Node.js 22 with ".mjs" files and implement ES module import syntax. To send responses to clients, the Lambda function constructs the endpoint URL using environment variables: |
| 75 | +`"https://" + process.env.API_ID + ".execute-api." + process.env.AWS_REGION + ".amazonaws.com/" + process.env.STAGE + "/"` and the command `PostToConnectionCommand` from the client [`ApiGatewayManagementApiClient`](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/apigatewaymanagementapi/). |
| 76 | +
|
| 77 | +## Testing |
| 78 | +
|
| 79 | +Once the template deployed, you would need to use a websocket client, I would recommend either Postman ior wscat. |
| 80 | +
|
| 81 | +1. Install wscat: |
| 82 | + ``` |
| 83 | + $ npm install -g wscat |
| 84 | + ``` |
| 85 | +
|
| 86 | +1. Connect to the WebSocket with the following command: |
| 87 | + ``` |
| 88 | + $ wscat --header token:hello -c wss://<websocket_url> |
| 89 | + ``` |
| 90 | +If you don't put the header and its value, you will get `Unauthorized` |
| 91 | +
|
| 92 | +You can then send the Json Payload to the `sendmessage` route: |
| 93 | +``` |
| 94 | +> {"action": "sendmessage","message" : "hey queen"} |
| 95 | +< good job on deploying this template, keep slaying!! |
| 96 | +``` |
| 97 | +
|
| 98 | +## Cleanup |
| 99 | + |
| 100 | +1. Delete the stack |
| 101 | + ```bash |
| 102 | + sam delete |
| 103 | + ``` |
| 104 | +
|
| 105 | +---- |
| 106 | +Copyright 2024 Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 107 | +
|
| 108 | +SPDX-License-Identifier: MIT-0 |
0 commit comments