-
Notifications
You must be signed in to change notification settings - Fork 979
adding jwt cognito pattern for websocket api using lambda authorizer #2384
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
Open
srajaw
wants to merge
8
commits into
aws-samples:main
Choose a base branch
from
srajaw:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
899f471
adding jwt cognito pattern for websocket api using lambda authorizer
6291d01
Update jwt_authorizer_websocket_api_lambda_authorizer/README.md
srajaw 754937e
Update jwt_authorizer_websocket_api_lambda_authorizer/README.md
srajaw e7a96b8
Update jwt_authorizer_websocket_api_lambda_authorizer/README.md
srajaw f955788
Update jwt_authorizer_websocket_api_lambda_authorizer/README.md
srajaw 1586496
Merge branch 'aws-samples:main' into main
srajaw 2670d00
added steps to get access token via cli
53e4685
updated readme file
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
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,81 @@ | ||
# Serverless JWT Authorizer for Websocket Amazon API Gateway with AWS Lambda Authorizer | ||
 | ||
|
||
This serverless pattern demonstrates how to authenticate and authorize users via a Lambda authorizer for an API Gateway WebSocket API using Amazon Cognito user pool tokens. | ||
|
||
Learn more about this pattern at Serverless Land Patterns: https://serverlessland.com/patterns/jwt_authorizer_websocket_api_lambda_authorizer | ||
|
||
Important: this ready-to-use 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) | ||
* [SAM Installed](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/install-sam-cli.html) | ||
* [Wscat Installed](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-how-to-call-websocket-api-wscat.html) | ||
* [Cognito User Pool](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools.html) | ||
|
||
## 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-pattern | ||
``` | ||
1. Change directory to the pattern directory: | ||
``` | ||
cd jwt_authorizer_websocket_api_lambda_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 the Stack Name | ||
- Enter a value: | ||
|
||
Enter the region in which you want to deploy the stack | ||
- Enter a value: *{enter the region for deployment}* | ||
|
||
Enter User Pool Id | ||
- Enter a value: | ||
|
||
Enter Client Id: | ||
- Enter a value: *{Client id of the app created in user pool}* | ||
|
||
|
||
1. Note the outputs from the deployment process. It contain the full url link which can be used for testing. | ||
|
||
## Testing | ||
1. Run the below commands to get the Authorization token for your user pool. | ||
``` | ||
echo -n "[username][app client ID]" | openssl dgst -sha256 -hmac [app client secret] -binary | openssl enc -base64 | ||
|
||
aws cognito-idp initiate-auth --auth-flow ADMIN_NO_SRP_AUTH --auth-parameters USERNAME=<username>,PASSWORD=<password>,SECRET_HASH=<secret_hash> --client-id <client-id> | ||
``` | ||
|
||
1. Copy the Access Token and save in a notepad | ||
|
||
1. Run the following websocket command to invoke the websocket Rest API with the retrieved access token: | ||
``` | ||
wscat -c wss://<apiId>.execute-api.<region>.amazonaws.com/prod/ -H Authorization:Xyz | ||
``` | ||
|
||
2. Observe the output of the above command, if it shows connected then you are able to successfully connected to the websocket API using JWT token. | ||
|
||
## Cleanup | ||
|
||
1. Change directory to the pattern directory: | ||
``` | ||
cd serverless-patterns/jwt_authorizer_websocket_api_lambda_authorizer | ||
``` | ||
1. Delete all created resources in same account. | ||
``` | ||
sam delete --stack-name <stackname> | ||
``` | ||
|
||
---- | ||
Copyright 2024 Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
|
||
SPDX-License-Identifier: MIT-0 |
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
58 changes: 58 additions & 0 deletions
58
jwt_authorizer_websocket_api_lambda_authorizer/src/authLambda/index.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,58 @@ | ||
import { CognitoJwtVerifier } from "aws-jwt-verify"; | ||
|
||
let userPoolId = process.env.userPoolId; | ||
let clientId = process.env.clientId; | ||
|
||
// Verifier that expects valid access tokens: | ||
const verifier = CognitoJwtVerifier.create({ | ||
userPoolId: userPoolId, | ||
tokenUse: "access", | ||
clientId: clientId, | ||
}); | ||
|
||
function generatePolicy(principalId, effect, resource) { | ||
const authResponse = { | ||
principalId, | ||
}; | ||
|
||
if (effect && resource) { | ||
const policyDocument = { | ||
Version: '2012-10-17', | ||
Statement: [ | ||
{ | ||
Action: 'execute-api:Invoke', | ||
Effect: effect, | ||
Resource: resource, | ||
}, | ||
], | ||
}; | ||
authResponse.policyDocument = policyDocument; | ||
} | ||
|
||
return JSON.stringify(authResponse); | ||
} | ||
|
||
function generateAllow(principalId, resource) { | ||
return generatePolicy(principalId, 'Allow', resource); | ||
} | ||
|
||
function generateDeny(principalId, resource) { | ||
return generatePolicy(principalId, 'Deny', resource); | ||
} | ||
|
||
export const handler = async (event) => { | ||
// TODO implement | ||
let Authtoken = event.headers.Authorization | ||
try { | ||
const payload = await verifier.verify( | ||
Authtoken | ||
); | ||
console.log("Token is valid. Payload:", payload); | ||
const response = generateAllow('me', event.methodArn); | ||
return JSON.parse(response); | ||
} catch { | ||
console.log('unauthorized'); | ||
const response = generateDeny('me', event.methodArn); | ||
return JSON.parse(response); | ||
} | ||
}; |
Binary file not shown.
5 changes: 5 additions & 0 deletions
5
jwt_authorizer_websocket_api_lambda_authorizer/src/onConnect/index.py
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,5 @@ | ||
import json | ||
|
||
def lambda_handler(event, context): | ||
print(event) | ||
return {"statusCode": 200, "body":"hello!!"} |
5 changes: 5 additions & 0 deletions
5
jwt_authorizer_websocket_api_lambda_authorizer/src/onDisconnect/index.py
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,5 @@ | ||
import json | ||
|
||
def lambda_handler(event, context): | ||
print(event) | ||
return {"statusCode": 200, "body":"Disconnecting, bye!"} |
5 changes: 5 additions & 0 deletions
5
jwt_authorizer_websocket_api_lambda_authorizer/src/sendMessage/index.py
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,5 @@ | ||
import json | ||
|
||
def lambda_handler(event, context): | ||
print(event) | ||
return {"statusCode": 200, "body":"how are you doing?"} |
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.