Skip to content

Commit e6315e9

Browse files
authored
Merge branch 'main' into issue#822
2 parents 26b5bc3 + a25bb9e commit e6315e9

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

43 files changed

+2686
-0
lines changed

java/cognito-api-lambda/.gitignore

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
.classpath.txt
2+
target
3+
.classpath
4+
.project
5+
.idea
6+
.settings
7+
.vscode
8+
*.iml
9+
10+
# CDK asset staging directory
11+
.cdk.staging
12+
cdk.out
13+

java/cognito-api-lambda/README.md

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
# APIGateway backed by Lambda and protected by a Cognito User Pool.
2+
3+
4+
<!--BEGIN STABILITY BANNER-->
5+
6+
---
7+
8+
![Stability: Stable](https://img.shields.io/badge/stability-Stable-success.svg?style=for-the-badge)
9+
10+
> **This is a stable example. It should successfully build out of the box**
11+
>
12+
> This example is built on Construct Libraries marked "Stable" and does not have any infrastructure prerequisites to build.
13+
14+
---
15+
<!--END STABILITY BANNER-->
16+
17+
This an example of an APIGateway that is protected with a Cognito User Pool, pointing to a Hello World Lambda.
18+
19+
## Build
20+
21+
To build this example, you need to be in this example's root directory. Then run the following:
22+
23+
```bash
24+
npm install -g aws-cdk
25+
npm install
26+
cdk synth
27+
```
28+
29+
This will install the necessary CDK, then this example's dependencies, and then build the CloudFormation template. The resulting CloudFormation template will be in the `cdk.out` directory.
30+
31+
## Deploy
32+
33+
Run `cdk deploy`.
34+
This will deploy / redeploy the Stack to AWS.
35+
After the deployment, the URL of the Rest API created will be available in the outputs of the CloudFormation stack and can be used to invoke the lambda function.
36+
At this point, if an HTTP GET request is attempted on the Rest API without including and `Authorization` header, a `401 - Unauthorized` response will be returned.
37+
In order for the authorization to succeed when the lambda function is invoked through the API Gateway, each request must include an `Authorization` HTTP header containing an access token obtained for the specific user from the user pool.
38+
39+
## The Component Structure
40+
41+
The main resources of the component are:
42+
43+
- A Lambda Function that returns the string "Hello world!"
44+
- A Rest API with a GET method that points to the Lambda Function
45+
- A Cognito User Pool
46+
- An Authorizer for the Rest API with the User Pool attached.
47+
48+
## Useful commands
49+
50+
* `mvn package` compile and run tests
51+
* `cdk ls` list all stacks in the app
52+
* `cdk synth` emits the synthesized CloudFormation template
53+
* `cdk deploy` deploy this stack to your default AWS account/region
54+
* `cdk diff` compare deployed stack with current state
55+
* `cdk docs` open CDK documentation

java/cognito-api-lambda/cdk.json

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
{
2+
"app": "mvn -e -q compile exec:java",
3+
"watch": {
4+
"include": [
5+
"**"
6+
],
7+
"exclude": [
8+
"README.md",
9+
"cdk*.json",
10+
"target",
11+
"pom.xml",
12+
"src/test"
13+
]
14+
},
15+
"context": {
16+
"@aws-cdk/aws-lambda:recognizeLayerVersion": true,
17+
"@aws-cdk/core:checkSecretUsage": true,
18+
"@aws-cdk/core:target-partitions": [
19+
"aws",
20+
"aws-cn"
21+
],
22+
"@aws-cdk-containers/ecs-service-extensions:enableDefaultLogDriver": true,
23+
"@aws-cdk/aws-ec2:uniqueImdsv2TemplateName": true,
24+
"@aws-cdk/aws-ecs:arnFormatIncludesClusterName": true,
25+
"@aws-cdk/aws-iam:minimizePolicies": true,
26+
"@aws-cdk/core:validateSnapshotRemovalPolicy": true,
27+
"@aws-cdk/aws-codepipeline:crossAccountKeyAliasStackSafeResourceName": true,
28+
"@aws-cdk/aws-s3:createDefaultLoggingPolicy": true,
29+
"@aws-cdk/aws-sns-subscriptions:restrictSqsDescryption": true,
30+
"@aws-cdk/aws-apigateway:disableCloudWatchRole": true,
31+
"@aws-cdk/core:enablePartitionLiterals": true,
32+
"@aws-cdk/aws-events:eventsTargetQueueSameAccount": true,
33+
"@aws-cdk/aws-ecs:disableExplicitDeploymentControllerForCircuitBreaker": true,
34+
"@aws-cdk/aws-iam:importedRoleStackSafeDefaultPolicyName": true,
35+
"@aws-cdk/aws-s3:serverAccessLogsUseBucketPolicy": true,
36+
"@aws-cdk/aws-route53-patters:useCertificate": true,
37+
"@aws-cdk/customresources:installLatestAwsSdkDefault": false,
38+
"@aws-cdk/aws-rds:databaseProxyUniqueResourceName": true,
39+
"@aws-cdk/aws-codedeploy:removeAlarmsFromDeploymentGroup": true,
40+
"@aws-cdk/aws-apigateway:authorizerChangeDeploymentLogicalId": true,
41+
"@aws-cdk/aws-ec2:launchTemplateDefaultUserData": true,
42+
"@aws-cdk/aws-secretsmanager:useAttachedSecretResourcePolicyForSecretTargetAttachments": true,
43+
"@aws-cdk/aws-redshift:columnId": true,
44+
"@aws-cdk/aws-stepfunctions-tasks:enableEmrServicePolicyV2": true,
45+
"@aws-cdk/aws-ec2:restrictDefaultSecurityGroup": true,
46+
"@aws-cdk/aws-apigateway:requestValidatorUniqueId": true,
47+
"@aws-cdk/aws-kms:aliasNameRef": true,
48+
"@aws-cdk/aws-autoscaling:generateLaunchTemplateInsteadOfLaunchConfig": true,
49+
"@aws-cdk/core:includePrefixInUniqueNameGeneration": true,
50+
"@aws-cdk/aws-efs:denyAnonymousAccess": true,
51+
"@aws-cdk/aws-opensearchservice:enableOpensearchMultiAzWithStandby": true,
52+
"@aws-cdk/aws-lambda-nodejs:useLatestRuntimeVersion": true,
53+
"@aws-cdk/aws-efs:mountTargetOrderInsensitiveLogicalId": true,
54+
"@aws-cdk/aws-rds:auroraClusterChangeScopeOfInstanceParameterGroupWithEachParameters": true,
55+
"@aws-cdk/aws-appsync:useArnForSourceApiAssociationIdentifier": true,
56+
"@aws-cdk/aws-rds:preventRenderingDeprecatedCredentials": true,
57+
"@aws-cdk/aws-codepipeline-actions:useNewDefaultBranchForCodeCommitSource": true,
58+
"@aws-cdk/aws-cloudwatch-actions:changeLambdaPermissionLogicalIdForLambdaAction": true,
59+
"@aws-cdk/aws-codepipeline:crossAccountKeysDefaultValueToFalse": true,
60+
"@aws-cdk/aws-codepipeline:defaultPipelineTypeToV2": true,
61+
"@aws-cdk/aws-kms:reduceCrossAccountRegionPolicyScope": true,
62+
"@aws-cdk/aws-eks:nodegroupNameAttribute": true,
63+
"@aws-cdk/aws-ec2:ebsDefaultGp3Volume": true,
64+
"@aws-cdk/aws-ecs:removeDefaultDeploymentAlarm": true,
65+
"@aws-cdk/custom-resources:logApiResponseDataPropertyTrueDefault": false,
66+
"@aws-cdk/aws-s3:keepNotificationInImportedBucket": false
67+
}
68+
}

java/cognito-api-lambda/pom.xml

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
3+
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
4+
<modelVersion>4.0.0</modelVersion>
5+
6+
<groupId>com.myorg</groupId>
7+
<artifactId>cognito-api-lambda</artifactId>
8+
<version>0.1</version>
9+
10+
<properties>
11+
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
12+
<cdk.version>2.158.0</cdk.version>
13+
<constructs.version>[10.0.0,11.0.0)</constructs.version>
14+
<junit.version>5.7.1</junit.version>
15+
</properties>
16+
17+
<build>
18+
<plugins>
19+
<plugin>
20+
<groupId>org.apache.maven.plugins</groupId>
21+
<artifactId>maven-compiler-plugin</artifactId>
22+
<version>3.11.0</version>
23+
<configuration>
24+
<release>17</release>
25+
</configuration>
26+
</plugin>
27+
28+
<plugin>
29+
<groupId>org.codehaus.mojo</groupId>
30+
<artifactId>exec-maven-plugin</artifactId>
31+
<version>3.1.0</version>
32+
<configuration>
33+
<mainClass>com.myorg.CognitoApiLambdaApp</mainClass>
34+
</configuration>
35+
</plugin>
36+
</plugins>
37+
</build>
38+
39+
<dependencies>
40+
<!-- AWS Cloud Development Kit -->
41+
<dependency>
42+
<groupId>software.amazon.awscdk</groupId>
43+
<artifactId>aws-cdk-lib</artifactId>
44+
<version>${cdk.version}</version>
45+
</dependency>
46+
47+
<dependency>
48+
<groupId>software.constructs</groupId>
49+
<artifactId>constructs</artifactId>
50+
<version>${constructs.version}</version>
51+
</dependency>
52+
53+
<dependency>
54+
<groupId>org.junit.jupiter</groupId>
55+
<artifactId>junit-jupiter</artifactId>
56+
<version>${junit.version}</version>
57+
<scope>test</scope>
58+
</dependency>
59+
</dependencies>
60+
</project>
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package com.myorg;
2+
3+
import software.amazon.awscdk.App;
4+
import software.amazon.awscdk.StackProps;
5+
6+
public class CognitoApiLambdaApp {
7+
public static void main(final String... args) {
8+
App app = new App();
9+
StackProps stackProps = StackProps.builder().build();
10+
new CognitoApiLambdaStack(app, "CognitoApiLambdaStack", stackProps);
11+
app.synth();
12+
}
13+
}
14+
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
package com.myorg;
2+
3+
import org.jetbrains.annotations.NotNull;
4+
import software.amazon.awscdk.RemovalPolicy;
5+
import software.amazon.awscdk.Stack;
6+
import software.amazon.awscdk.StackProps;
7+
import software.amazon.awscdk.services.apigateway.*;
8+
import software.amazon.awscdk.services.cognito.SignInAliases;
9+
import software.amazon.awscdk.services.cognito.UserPool;
10+
import software.amazon.awscdk.services.lambda.InlineCode;
11+
import software.amazon.awscdk.services.lambda.Runtime;
12+
import software.amazon.awscdk.services.lambda.SingletonFunction;
13+
import software.constructs.Construct;
14+
15+
import java.io.IOException;
16+
import java.nio.file.Files;
17+
import java.nio.file.Path;
18+
import java.util.List;
19+
20+
public class CognitoApiLambdaStack extends Stack {
21+
22+
private record Authorizer(CfnAuthorizer authorizer) implements IAuthorizer {
23+
@Override
24+
public @NotNull String getAuthorizerId() {
25+
return authorizer.getRef();
26+
}
27+
}
28+
29+
public CognitoApiLambdaStack(final Construct scope, final String id, final StackProps props) {
30+
super(scope, id, props);
31+
var helloWorldFunction = SingletonFunction.Builder.create(this, "helloWorldFunction")
32+
.functionName("helloWorldFunction")
33+
.code(InlineCode.fromInline(getInlineCode()))
34+
.handler("index.handler")
35+
.runtime(Runtime.PYTHON_3_12)
36+
.uuid("")
37+
.build();
38+
var helloWorldLambdaRestApi = LambdaRestApi.Builder.create(this, "helloWorldLambdaRestApi")
39+
.restApiName("Hello World API")
40+
.cloudWatchRole(true)
41+
.cloudWatchRoleRemovalPolicy(RemovalPolicy.DESTROY)
42+
.handler(helloWorldFunction)
43+
.proxy(false)
44+
.build();
45+
var signInAliases = SignInAliases.builder()
46+
.email(true)
47+
.build();
48+
var userPool = UserPool.Builder.create(this, "userPool")
49+
.signInAliases(signInAliases)
50+
.removalPolicy(RemovalPolicy.DESTROY)
51+
.build();
52+
var authorizer = new Authorizer(
53+
CfnAuthorizer.Builder.create(this, "cfnAuth")
54+
.restApiId(helloWorldLambdaRestApi.getRestApiId())
55+
.name("HelloWorldAPIAuthorizer")
56+
.type("COGNITO_USER_POOLS")
57+
.identitySource("method.request.header.Authorization")
58+
.providerArns(List.of(userPool.getUserPoolArn()))
59+
.build()
60+
);
61+
var helloResource = helloWorldLambdaRestApi.getRoot().addResource("HELLO");
62+
var methodOptions = MethodOptions.builder()
63+
.authorizationType(AuthorizationType.COGNITO)
64+
.authorizer(authorizer)
65+
.build();
66+
helloResource.addMethod("GET", new LambdaIntegration(helloWorldFunction), methodOptions);
67+
}
68+
69+
private String getInlineCode() {
70+
try {
71+
return new String(Files.readAllBytes(Path.of("src/main/resources/lambda/hello-world.py")));
72+
} catch (IOException e) {
73+
throw new RuntimeException(e);
74+
}
75+
}
76+
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
import json
2+
3+
def handler(event, context):
4+
print(event)
5+
return {
6+
'statusCode': 200,
7+
'body': 'Hello world!'
8+
}

0 commit comments

Comments
 (0)