Skip to content

Commit 191ef17

Browse files
authored
Merge pull request #2609 from aliceinaws/aliceinaws-feature-websocket-api-mapping-template
New serverless pattern - apigw-websocket-mapping-template-authorizer
2 parents 54d369f + ba19357 commit 191ef17

File tree

9 files changed

+634
-0
lines changed

9 files changed

+634
-0
lines changed
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
{
2+
"folders": [
3+
{
4+
"path": "../apigw-rest-regional-lambda"
5+
},
6+
{
7+
"path": ".."
8+
}
9+
],
10+
"settings": {}
11+
}
Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
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
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
{
2+
"title": "Websocket API Gateway with an AWS Lambda Authorizer and mapping template",
3+
"description": "Create a Websocket API with a Lambda Authorizer and an AWS Lambda in the back-end.",
4+
"language": "Node.js",
5+
"level": "200",
6+
"framework": "AWS SAM",
7+
"introBox": {
8+
"headline": "How it works",
9+
"text": [
10+
"This projects demonstrates how to use a WebSocket API with an AWS Lambda Authorizer",
11+
"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.",
12+
"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"
13+
]
14+
},
15+
"gitHub": {
16+
"template": {
17+
"repoURL": "https://github.com/aws-samples/serverless-patterns/tree/main/apigw-websocket-mapping-template-authorizer",
18+
"templateURL": "serverless-patterns/apigw-websocket-mapping-template-authorizer",
19+
"projectFolder": "apigw-websocket-mapping-template-authorizer",
20+
"templateFile": "template.yaml"
21+
}
22+
},
23+
"resources": {
24+
"bullets": [
25+
{
26+
"text": "Invoke a Webscoket API with wscat",
27+
"link": "https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-how-to-call-websocket-api-wscat.html"
28+
},
29+
{
30+
"text": "Integration request in Websocket API Gateway",
31+
"link": "https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-integration-requests.html"
32+
},
33+
{
34+
"text": "Control access to WebSocket APIs with AWS Lambda REQUEST authorizers",
35+
"link": "https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-lambda-auth.html"
36+
}
37+
]
38+
},
39+
"deploy": {
40+
"text": ["sam deploy"]
41+
},
42+
"testing": {
43+
"text": ["See the GitHub repo for detailed testing instructions."]
44+
},
45+
"cleanup": {
46+
"text": ["Delete the stack: <code>sam delete</code>."]
47+
},
48+
"authors": [
49+
{
50+
"name": "Alice Goumain",
51+
"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",
52+
"bio": "Cloud Support Engineer in Serverless @ AWS",
53+
"linkedin": "alice-goumain/"
54+
}
55+
],
56+
"patternArch": {
57+
"icon1": {
58+
"x": 20,
59+
"y": 50,
60+
"service": "apigw",
61+
"label": "API Gateway WebSocket"
62+
},
63+
"icon2": {
64+
"x": 50,
65+
"y": 50,
66+
"service": "lambda",
67+
"label": "AWS Lambda"
68+
},
69+
"icon3": {
70+
"x": 80,
71+
"y": 50,
72+
"service": "dynamodb",
73+
"label": "Amazon DynamoDB"
74+
},
75+
"line1": {
76+
"from": "icon1",
77+
"to": "icon2",
78+
"label": ""
79+
},
80+
"line2": {
81+
"from": "icon2",
82+
"to": "icon3",
83+
"label": ""
84+
}
85+
}
86+
}
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
{
2+
"title": "AWS Websocket API Gateway with an AWS Lambda Authorizer and mapping template",
3+
"description": "Create a Websocket API with a Lambda authorizer and a Lambda in the back-end.",
4+
"language": "NodeJs",
5+
"level": "200",
6+
"framework": "SAM",
7+
"introBox": {
8+
"headline": "How it works",
9+
"text": [
10+
"This projects demonstrates how to use an AWS WebSocket API with an AWS Lambda Authorizer",
11+
"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.",
12+
"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"
13+
]
14+
},
15+
"gitHub": {
16+
"template": {
17+
"repoURL": "https://github.com/aws-samples/serverless-patterns/tree/main/apigw-websocket-mapping-template-authorizer",
18+
"templateURL": "serverless-patterns/apigw-websocket-mapping-template-authorizer",
19+
"projectFolder": "apigw-websocket-mapping-template-authorizer",
20+
"templateFile": "apigw-websocket-mapping-template-authorizer/template.yaml"
21+
}
22+
},
23+
"resources": {
24+
"bullets": [
25+
{
26+
"text": "Invoke a Webscoket API with wscat",
27+
"link": "https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-how-to-call-websocket-api-wscat.html"
28+
},
29+
{
30+
"text": "Integration request in Websocket API Gateway",
31+
"link": "https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-integration-requests.html"
32+
},
33+
{
34+
"text": "Control access to WebSocket APIs with AWS Lambda REQUEST authorizers",
35+
"link": "https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-lambda-auth.html"
36+
}
37+
]
38+
},
39+
"deploy": {
40+
"text": [
41+
"sam deploy"
42+
]
43+
},
44+
"testing": {
45+
"text": [
46+
"See the GitHub repo for detailed testing instructions."
47+
]
48+
},
49+
"cleanup": {
50+
"text": [
51+
"Delete the stack: <code>sam delete</code>."
52+
]
53+
},
54+
"authors": [
55+
{
56+
"name": "Alice Goumain",
57+
"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",
58+
"bio": "Cloud Support Engineer in Serverless @ AWS",
59+
"linkedin": "https://www.linkedin.com/in/alice-goumain/"
60+
}
61+
]
62+
}
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
export const handler = function(event, context, callback) {
2+
console.log('Received event:', JSON.stringify(event, null, 2));
3+
// Retrieve request parameters from the Lambda function input:
4+
var headers = event.headers;
5+
if (headers.token === "hello"){
6+
callback(null, generateAllow('me', event.methodArn));
7+
} else {
8+
callback("Unauthorized");
9+
}
10+
}
11+
// Help function to generate an IAM policy
12+
var generatePolicy = function(principalId, effect, resource) {
13+
// Required output:
14+
var authResponse = {};
15+
authResponse.principalId = principalId;
16+
if (effect && resource) {
17+
var policyDocument = {};
18+
policyDocument.Version = '2012-10-17'; // default version
19+
policyDocument.Statement = [];
20+
var statementOne = {};
21+
statementOne.Action = 'execute-api:Invoke'; // default action
22+
statementOne.Effect = effect;
23+
statementOne.Resource = resource;
24+
policyDocument.Statement[0] = statementOne;
25+
authResponse.policyDocument = policyDocument;
26+
}
27+
return authResponse;
28+
}
29+
30+
var generateAllow = function(principalId, resource) {
31+
return generatePolicy(principalId, 'Allow', resource);
32+
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import { DynamoDBClient, PutItemCommand } from "@aws-sdk/client-dynamodb";
2+
const client = new DynamoDBClient({ region: process.env.AWS_REGION });
3+
4+
export const handler = async (event) => {
5+
const connectionId = event.requestContext.connectionId;
6+
console.log("connection ID:", JSON.stringify(connectionId, null, 2) ); // Print the connection ID
7+
const putParams = {
8+
"Item": {
9+
"connectionId": {
10+
"S": connectionId
11+
},
12+
},
13+
"TableName": process.env.TABLE_NAME
14+
};
15+
try {
16+
const command = new PutItemCommand(putParams);
17+
const response = await client.send(command);
18+
console.log("put command:", JSON.stringify(response, null, 2)); // Print the response
19+
} catch (err) {
20+
return { statusCode: 500, body: "Failed to connect: " + JSON.stringify(err) };
21+
}
22+
23+
return { statusCode: 200, body: "Connected." };
24+
};
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import { DynamoDBClient, DeleteItemCommand } from "@aws-sdk/client-dynamodb";
2+
const client = new DynamoDBClient({ region: process.env.AWS_REGION });
3+
4+
export const handler = async (event) => {
5+
const connectionId = event.requestContext.connectionId;
6+
const deleteParams = {
7+
"Key": {
8+
"connectionId": {
9+
"S": connectionId
10+
},
11+
},
12+
"TableName": process.env.TABLE_NAME
13+
};
14+
15+
try {
16+
const command = new DeleteItemCommand(deleteParams);
17+
await client.send(command);
18+
} catch (err) {
19+
return { statusCode: 500, body: "Failed to disconnect: " + JSON.stringify(err) };
20+
}
21+
22+
return { statusCode: 200, body: "Disconnected." };
23+
};

0 commit comments

Comments
 (0)