generated from amazon-archives/__template_MIT-0
-
Notifications
You must be signed in to change notification settings - Fork 1k
New serverless pattern - apigw-websocket-mapping-template-authorizer #2609
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
julianwood
merged 15 commits into
aws-samples:main
from
aliceincloudland:aliceinaws-feature-websocket-api-mapping-template
Jun 13, 2025
Merged
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
5572fd1
adding Lambda function code and template
aliceaws 25c9ba4
added the Read.me file and more stuff
aliceaws f85e367
added a few bits
aliceaws cc79fdc
added a few bits
aliceaws 3ec1323
added a few bits
aliceaws 2a7d194
added a few bits
aliceaws a67620d
added a few bits
aliceaws 8336cf2
added a few bits
aliceaws 5a09a17
added a few bits
aliceaws ff66993
added a few bits
aliceaws a36cbbf
added all the fixes and made some changes to the description
aliceaws 4caf924
added the same delete in README
aliceaws fa2d172
modifications to JSON file
aliceaws 4152249
added the modifications
aliceaws ba19357
Create apigw-websocket-mapping-template-authorizer.json
marcojahn File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
11 changes: 11 additions & 0 deletions
11
apigw-http-api-lambda-python/apigw-rest-regional-lambda.code-workspace
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| { | ||
| "folders": [ | ||
| { | ||
| "path": "../apigw-rest-regional-lambda" | ||
| }, | ||
| { | ||
| "path": ".." | ||
| } | ||
| ], | ||
| "settings": {} | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,108 @@ | ||
| # AWS API Gateway Websocket API to AWS Lambda with authorization and mapping template | ||
|
|
||
| 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. | ||
|
|
||
| Learn more about this pattern at Serverless Land Patterns: https://serverlessland.com/patterns/apigw-websocket-mapping-template-authorizer | ||
|
|
||
| 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. | ||
|
|
||
| ## Requirements | ||
|
|
||
| * [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. | ||
| * [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html) installed and configured | ||
| * [Git Installed](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) | ||
| * [AWS Serverless Application Model](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html) (AWS SAM) installed | ||
| * [Install NPM](https://www.npmjs.com/get-npm). | ||
|
|
||
| ## Deployment Instructions | ||
|
|
||
| 1. Create a new directory, navigate to that directory in a terminal and clone the GitHub repository: | ||
| ``` | ||
| git clone https://github.com/aws-samples/serverless-patterns | ||
| ``` | ||
| 1. Change directory to the pattern directory: | ||
| ``` | ||
| cd apigw-websocket-mapping-template-authorizer | ||
| ``` | ||
| 1. From the command line, use AWS SAM to deploy the AWS resources for the pattern as specified in the template.yml file: | ||
| ``` | ||
| sam deploy --guided | ||
| ``` | ||
| 1. During the prompts: | ||
| * Enter a stack name | ||
| * Enter the desired AWS Region | ||
| * Allow SAM CLI to create IAM roles with the required permissions. | ||
|
|
||
| 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. | ||
|
|
||
| 1. Note the outputs from the SAM deployment process. These contain the resource names and/or ARNs which are used for testing. | ||
|
|
||
| ## How it works | ||
|
|
||
| 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. | ||
|
|
||
|
|
||
| The Mapping Template used is this one : | ||
| ``` | ||
| { | ||
| "requestContext": { | ||
| "routeKey": "$context.routeKey", | ||
| "messageId": "$context.messageId", | ||
| "auth": "$context.authorizer.principalId", | ||
| "token": "$context.authorizer.token", | ||
| "eventType": "$context.eventType", | ||
| "extendedRequestId": "$context.extendedRequestId", | ||
| "requestTime": "$context.requestTime", | ||
| "messageDirection": "$context.messageDirection", | ||
| "stage": "$context.stage", | ||
| "connectedAt": "$context.connectedAt", | ||
| "requestTimeEpoch": "$context.requestTimeEpoch", | ||
| "sourceIp": "$context.identity.sourceIp", | ||
| "requestId": "$context.requestId", | ||
| "domainName": "$context.domainName", | ||
| "connectionId": "$context.connectionId", | ||
| "apiId": "$context.apiId" | ||
| }, | ||
| "body": "$util.escapeJavaScript($input.body)", | ||
| "isBase64Encoded": "$context.isBase64Encoded" | ||
| } | ||
| ``` | ||
| 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. | ||
|
|
||
| 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. | ||
|
|
||
| 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: | ||
| `"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/). | ||
|
|
||
| ## Testing | ||
|
|
||
| Once the template deployed, you would need to use a websocket client, I would recommend either Postman ior wscat. | ||
|
|
||
| 1. Install wscat: | ||
| ``` | ||
| $ npm install -g wscat | ||
| ``` | ||
|
|
||
| 1. Connect to the WebSocket with the following command: | ||
| ``` | ||
| $ wscat --header token:hello -c wss://<websocket_url> | ||
| ``` | ||
| If you don't put the header and its value, you will get `Unauthorized` | ||
|
|
||
| You can then send the Json Payload to the `sendmessage` route: | ||
| ``` | ||
| > {"action": "sendmessage","message" : "hey queen"} | ||
| < good job on deploying this template, keep slaying!! | ||
| ``` | ||
|
|
||
| ## Cleanup | ||
|
|
||
| 1. Delete the stack | ||
| ```bash | ||
| sam delete | ||
| ``` | ||
|
|
||
| ---- | ||
| Copyright 2024 Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
|
|
||
| SPDX-License-Identifier: MIT-0 | ||
86 changes: 86 additions & 0 deletions
86
apigw-websocket-mapping-template-authorizer/apigw-websocket-mapping-template-authorizer.json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,86 @@ | ||
| { | ||
| "title": "Websocket API Gateway with an AWS Lambda Authorizer and mapping template", | ||
| "description": "Create a Websocket API with a Lambda Authorizer and an AWS Lambda in the back-end.", | ||
| "language": "Node.js", | ||
| "level": "200", | ||
| "framework": "AWS SAM", | ||
| "introBox": { | ||
| "headline": "How it works", | ||
| "text": [ | ||
| "This projects demonstrates how to use a WebSocket API with an AWS Lambda Authorizer", | ||
| "The WebSocket API does not have a Proxy integration with the back-end Lambda Function written NodeJs 22, instead it is using a mapping template that forwards the main information of the request.", | ||
| "The Connection ID is stored in a Amazon DynamoDB table and the Lambda Function sends a response to the websocket API through the endpoint URL" | ||
| ] | ||
| }, | ||
| "gitHub": { | ||
| "template": { | ||
| "repoURL": "https://github.com/aws-samples/serverless-patterns/tree/main/apigw-websocket-mapping-template-authorizer", | ||
| "templateURL": "serverless-patterns/apigw-websocket-mapping-template-authorizer", | ||
| "projectFolder": "apigw-websocket-mapping-template-authorizer", | ||
| "templateFile": "template.yaml" | ||
| } | ||
| }, | ||
| "resources": { | ||
| "bullets": [ | ||
| { | ||
| "text": "Invoke a Webscoket API with wscat", | ||
| "link": "https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-how-to-call-websocket-api-wscat.html" | ||
| }, | ||
| { | ||
| "text": "Integration request in Websocket API Gateway", | ||
| "link": "https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-integration-requests.html" | ||
| }, | ||
| { | ||
| "text": "Control access to WebSocket APIs with AWS Lambda REQUEST authorizers", | ||
| "link": "https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-lambda-auth.html" | ||
| } | ||
| ] | ||
| }, | ||
| "deploy": { | ||
| "text": ["sam deploy"] | ||
| }, | ||
| "testing": { | ||
| "text": ["See the GitHub repo for detailed testing instructions."] | ||
| }, | ||
| "cleanup": { | ||
| "text": ["Delete the stack: <code>sam delete</code>."] | ||
| }, | ||
| "authors": [ | ||
| { | ||
| "name": "Alice Goumain", | ||
| "image": "https://media.licdn.com/dms/image/v2/C4E03AQFu1xnGt76xzg/profile-displayphoto-shrink_200_200/profile-displayphoto-shrink_200_200/0/1662636937225?e=2147483647&v=beta&t=f4IFRXMLweHD9WieD3X1D3YkZO3Hf-bdTXHAfYcFpbo", | ||
| "bio": "Cloud Support Engineer in Serverless @ AWS", | ||
| "linkedin": "alice-goumain/" | ||
| } | ||
| ], | ||
| "patternArch": { | ||
| "icon1": { | ||
| "x": 20, | ||
| "y": 50, | ||
| "service": "apigw", | ||
| "label": "API Gateway WebSocket" | ||
| }, | ||
| "icon2": { | ||
| "x": 50, | ||
| "y": 50, | ||
| "service": "lambda", | ||
| "label": "AWS Lambda" | ||
| }, | ||
| "icon3": { | ||
| "x": 80, | ||
| "y": 50, | ||
| "service": "dynamodb", | ||
| "label": "Amazon DynamoDB" | ||
| }, | ||
| "line1": { | ||
| "from": "icon1", | ||
| "to": "icon2", | ||
| "label": "" | ||
| }, | ||
| "line2": { | ||
| "from": "icon2", | ||
| "to": "icon3", | ||
| "label": "" | ||
| } | ||
| } | ||
| } |
62 changes: 62 additions & 0 deletions
62
apigw-websocket-mapping-template-authorizer/example-pattern.json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,62 @@ | ||
| { | ||
| "title": "AWS Websocket API Gateway with an AWS Lambda Authorizer and mapping template", | ||
| "description": "Create a Websocket API with a Lambda authorizer and a Lambda in the back-end.", | ||
| "language": "NodeJs", | ||
| "level": "200", | ||
| "framework": "SAM", | ||
| "introBox": { | ||
| "headline": "How it works", | ||
| "text": [ | ||
| "This projects demonstrates how to use an AWS WebSocket API with an AWS Lambda Authorizer", | ||
| "The WebSocket API does not have a Proxy integration with the back-end Lambda Function written NodeJs 22, instead it is using a mapping template that forwards the main information of the request.", | ||
| "The Connection ID is stored in an AWS DynamoDB table and the Lambda Function sends a response to the websocket API through the endpoint URL" | ||
| ] | ||
| }, | ||
| "gitHub": { | ||
| "template": { | ||
| "repoURL": "https://github.com/aws-samples/serverless-patterns/tree/main/apigw-websocket-mapping-template-authorizer", | ||
| "templateURL": "serverless-patterns/apigw-websocket-mapping-template-authorizer", | ||
| "projectFolder": "apigw-websocket-mapping-template-authorizer", | ||
| "templateFile": "apigw-websocket-mapping-template-authorizer/template.yaml" | ||
| } | ||
| }, | ||
| "resources": { | ||
| "bullets": [ | ||
| { | ||
| "text": "Invoke a Webscoket API with wscat", | ||
| "link": "https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-how-to-call-websocket-api-wscat.html" | ||
| }, | ||
| { | ||
| "text": "Integration request in Websocket API Gateway", | ||
| "link": "https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-integration-requests.html" | ||
| }, | ||
| { | ||
| "text": "Control access to WebSocket APIs with AWS Lambda REQUEST authorizers", | ||
| "link": "https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-lambda-auth.html" | ||
| } | ||
| ] | ||
| }, | ||
| "deploy": { | ||
| "text": [ | ||
| "sam deploy" | ||
| ] | ||
| }, | ||
| "testing": { | ||
| "text": [ | ||
| "See the GitHub repo for detailed testing instructions." | ||
| ] | ||
| }, | ||
| "cleanup": { | ||
| "text": [ | ||
| "Delete the stack: <code>sam delete</code>." | ||
| ] | ||
| }, | ||
| "authors": [ | ||
| { | ||
| "name": "Alice Goumain", | ||
| "image": "https://media.licdn.com/dms/image/v2/C4E03AQFu1xnGt76xzg/profile-displayphoto-shrink_200_200/profile-displayphoto-shrink_200_200/0/1662636937225?e=2147483647&v=beta&t=f4IFRXMLweHD9WieD3X1D3YkZO3Hf-bdTXHAfYcFpbo", | ||
| "bio": "Cloud Support Engineer in Serverless @ AWS", | ||
| "linkedin": "https://www.linkedin.com/in/alice-goumain/" | ||
| } | ||
| ] | ||
| } |
32 changes: 32 additions & 0 deletions
32
apigw-websocket-mapping-template-authorizer/src/authorizer.mjs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,32 @@ | ||
| export const handler = function(event, context, callback) { | ||
| console.log('Received event:', JSON.stringify(event, null, 2)); | ||
| // Retrieve request parameters from the Lambda function input: | ||
| var headers = event.headers; | ||
| if (headers.token === "hello"){ | ||
| callback(null, generateAllow('me', event.methodArn)); | ||
| } else { | ||
| callback("Unauthorized"); | ||
| } | ||
| } | ||
| // Help function to generate an IAM policy | ||
| var generatePolicy = function(principalId, effect, resource) { | ||
| // Required output: | ||
| var authResponse = {}; | ||
| authResponse.principalId = principalId; | ||
| if (effect && resource) { | ||
| var policyDocument = {}; | ||
| policyDocument.Version = '2012-10-17'; // default version | ||
| policyDocument.Statement = []; | ||
| var statementOne = {}; | ||
| statementOne.Action = 'execute-api:Invoke'; // default action | ||
| statementOne.Effect = effect; | ||
| statementOne.Resource = resource; | ||
| policyDocument.Statement[0] = statementOne; | ||
| authResponse.policyDocument = policyDocument; | ||
| } | ||
| return authResponse; | ||
| } | ||
|
|
||
| var generateAllow = function(principalId, resource) { | ||
| return generatePolicy(principalId, 'Allow', resource); | ||
| } |
24 changes: 24 additions & 0 deletions
24
apigw-websocket-mapping-template-authorizer/src/onconnect.mjs
marcojahn marked this conversation as resolved.
Show resolved
Hide resolved
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| import { DynamoDBClient, PutItemCommand } from "@aws-sdk/client-dynamodb"; | ||
| const client = new DynamoDBClient({ region: process.env.AWS_REGION }); | ||
|
|
||
| export const handler = async (event) => { | ||
| const connectionId = event.requestContext.connectionId; | ||
| console.log("connection ID:", JSON.stringify(connectionId, null, 2) ); // Print the connection ID | ||
| const putParams = { | ||
| "Item": { | ||
| "connectionId": { | ||
| "S": connectionId | ||
| }, | ||
| }, | ||
| "TableName": process.env.TABLE_NAME | ||
| }; | ||
| try { | ||
| const command = new PutItemCommand(putParams); | ||
| const response = await client.send(command); | ||
| console.log("put command:", JSON.stringify(response, null, 2)); // Print the response | ||
| } catch (err) { | ||
| return { statusCode: 500, body: "Failed to connect: " + JSON.stringify(err) }; | ||
| } | ||
|
|
||
| return { statusCode: 200, body: "Connected." }; | ||
| }; |
23 changes: 23 additions & 0 deletions
23
apigw-websocket-mapping-template-authorizer/src/ondisconnect.mjs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| import { DynamoDBClient, DeleteItemCommand } from "@aws-sdk/client-dynamodb"; | ||
| const client = new DynamoDBClient({ region: process.env.AWS_REGION }); | ||
|
|
||
| export const handler = async (event) => { | ||
| const connectionId = event.requestContext.connectionId; | ||
| const deleteParams = { | ||
| "Key": { | ||
| "connectionId": { | ||
| "S": connectionId | ||
| }, | ||
| }, | ||
| "TableName": process.env.TABLE_NAME | ||
| }; | ||
|
|
||
| try { | ||
| const command = new DeleteItemCommand(deleteParams); | ||
| await client.send(command); | ||
| } catch (err) { | ||
| return { statusCode: 500, body: "Failed to disconnect: " + JSON.stringify(err) }; | ||
| } | ||
|
|
||
| return { statusCode: 200, body: "Disconnected." }; | ||
| }; |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.