Created
December 10, 2020 09:38
-
-
Save Dzhuneyt/06e5829e5e331f3c4667b4a60a12080b to your computer and use it in GitHub Desktop.
Create a Cognito User Pool and the first user, programmatically, using AWS CDK and Custom Resources
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
import {UserPool} from '@aws-cdk/aws-cognito'; | |
import {Construct, Duration} from '@aws-cdk/core'; | |
import {AwsCustomResource, AwsCustomResourcePolicy, PhysicalResourceId} from '@aws-cdk/custom-resources'; | |
export class Cognito extends Construct { | |
public userPool: UserPool; | |
constructor(scope: Construct, id: string) { | |
super(scope, id); | |
const ADMIN_USERNAME = 'admin'; | |
const ADMIN_PASSWORD = 'password'; | |
this.userPool = new UserPool(this, 'Default', { | |
userPoolName: "TaxiApp", | |
autoVerify: {email: true}, | |
passwordPolicy: { | |
minLength: 6, | |
requireDigits: false, | |
requireLowercase: false, | |
requireSymbols: false, | |
requireUppercase: false, | |
tempPasswordValidity: Duration.days(90), | |
}, | |
}); | |
const createFirstAdmin = new AwsCustomResource(this, 'createFirstAdmin', { | |
onCreate: { | |
service: 'CognitoIdentityServiceProvider', | |
action: 'adminCreateUser', | |
parameters: { | |
UserPoolId: this.userPool.userPoolId, | |
Username: ADMIN_USERNAME, | |
MessageAction: 'SUPPRESS', | |
TemporaryPassword: ADMIN_PASSWORD, | |
}, | |
physicalResourceId: PhysicalResourceId.of(`createFirstAdmin_${ADMIN_USERNAME}`), | |
}, | |
onDelete: { | |
service: "CognitoIdentityServiceProvider", | |
action: "adminDeleteUser", | |
parameters: { | |
UserPoolId: this.userPool.userPoolId, | |
Username: ADMIN_USERNAME, | |
}, | |
}, | |
policy: AwsCustomResourcePolicy.fromSdkCalls({resources: AwsCustomResourcePolicy.ANY_RESOURCE}), | |
}); | |
const forceAdminPassword = new AwsCustomResource(this, 'forceAdminPassword', { | |
onCreate: { | |
service: 'CognitoIdentityServiceProvider', | |
action: 'adminSetUserPassword', | |
parameters: { | |
UserPoolId: this.userPool.userPoolId, | |
Username: ADMIN_USERNAME, | |
Permanent: true, | |
Password: ADMIN_PASSWORD, | |
}, | |
physicalResourceId: PhysicalResourceId.of('forceAdminPassword'), | |
}, | |
policy: AwsCustomResourcePolicy.fromSdkCalls({resources: AwsCustomResourcePolicy.ANY_RESOURCE}), | |
}); | |
forceAdminPassword.node.addDependency(createFirstAdmin); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment