|
| 1 | +import { CfnOutput, CfnResource, CustomResource, Duration, RemovalPolicy, Stack } from 'aws-cdk-lib'; |
| 2 | +import { ICertificate } from 'aws-cdk-lib/aws-certificatemanager'; |
| 3 | +import { CfnManagedLoginBranding, ManagedLoginVersion, UserPool, UserPoolClient } from 'aws-cdk-lib/aws-cognito'; |
| 4 | +import { Code, Runtime, SingletonFunction } from 'aws-cdk-lib/aws-lambda'; |
| 5 | +import { CnameRecord, IHostedZone } from 'aws-cdk-lib/aws-route53'; |
| 6 | +import { AwsCustomResource, AwsCustomResourcePolicy, PhysicalResourceId } from 'aws-cdk-lib/custom-resources'; |
| 7 | +import { Construct } from 'constructs'; |
| 8 | +import { readFileSync } from 'fs'; |
| 9 | +import { join } from 'path'; |
| 10 | + |
| 11 | +export interface AuthProps { |
| 12 | + readonly hostedZone?: IHostedZone; |
| 13 | + readonly sharedCertificate?: ICertificate; |
| 14 | +} |
| 15 | + |
| 16 | +export class Auth extends Construct { |
| 17 | + readonly userPool: UserPool; |
| 18 | + readonly client: UserPoolClient; |
| 19 | + readonly domainName: string; |
| 20 | + |
| 21 | + private callbackUrlCount = 0; |
| 22 | + |
| 23 | + constructor(scope: Construct, id: string, props: AuthProps) { |
| 24 | + super(scope, id); |
| 25 | + const { hostedZone } = props; |
| 26 | + const subDomain = 'auth'; |
| 27 | + let domainPrefix = ''; |
| 28 | + if (!hostedZone) { |
| 29 | + // When we do not use a custom domain, we must make domainPrefix unique in the AWS region. |
| 30 | + // To avoid a collision, we generate a random string with CFn custom resource. |
| 31 | + const generator = new SingletonFunction(this, 'RandomStringGenerator', { |
| 32 | + runtime: Runtime.NODEJS_22_X, |
| 33 | + handler: 'index.handler', |
| 34 | + timeout: Duration.seconds(5), |
| 35 | + lambdaPurpose: 'RandomStringGenerator', |
| 36 | + uuid: '11e9c903-f11a-4989-833c-985dddef5eb2', |
| 37 | + code: Code.fromInline(readFileSync(join(__dirname, 'prefix-generator.js')).toString()), |
| 38 | + }); |
| 39 | + |
| 40 | + const domainPrefixResource = new CustomResource(this, 'DomainPrefix', { |
| 41 | + serviceToken: generator.functionArn, |
| 42 | + resourceType: 'Custom::RandomString', |
| 43 | + properties: { prefix: 'webapp-', length: 10 }, |
| 44 | + serviceTimeout: Duration.seconds(10), |
| 45 | + }); |
| 46 | + domainPrefix = domainPrefixResource.getAttString('generated'); |
| 47 | + } |
| 48 | + |
| 49 | + this.domainName = hostedZone |
| 50 | + ? `${subDomain}.${hostedZone.zoneName}` |
| 51 | + : `${domainPrefix}.auth.${Stack.of(this).region}.amazoncognito.com`; |
| 52 | + |
| 53 | + const userPool = new UserPool(this, 'UserPool', { |
| 54 | + passwordPolicy: { |
| 55 | + requireUppercase: true, |
| 56 | + requireSymbols: true, |
| 57 | + requireDigits: true, |
| 58 | + minLength: 8, |
| 59 | + }, |
| 60 | + selfSignUpEnabled: true, |
| 61 | + signInAliases: { |
| 62 | + username: false, |
| 63 | + email: true, |
| 64 | + }, |
| 65 | + removalPolicy: RemovalPolicy.DESTROY, |
| 66 | + }); |
| 67 | + |
| 68 | + const client = userPool.addClient(`Client`, { |
| 69 | + idTokenValidity: Duration.days(1), |
| 70 | + authFlows: { |
| 71 | + userPassword: true, |
| 72 | + userSrp: true, |
| 73 | + }, |
| 74 | + oAuth: { |
| 75 | + flows: { |
| 76 | + authorizationCodeGrant: true, |
| 77 | + }, |
| 78 | + callbackUrls: ['http://localhost/dummy'], |
| 79 | + logoutUrls: ['http://localhost/dummy'], |
| 80 | + }, |
| 81 | + }); |
| 82 | + |
| 83 | + this.client = client; |
| 84 | + this.userPool = userPool; |
| 85 | + |
| 86 | + const domain = userPool.addDomain('CognitoDomain', { |
| 87 | + ...(hostedZone && props.sharedCertificate |
| 88 | + ? { |
| 89 | + customDomain: { |
| 90 | + domainName: this.domainName, |
| 91 | + certificate: props.sharedCertificate, |
| 92 | + }, |
| 93 | + } |
| 94 | + : { |
| 95 | + cognitoDomain: { |
| 96 | + domainPrefix, |
| 97 | + }, |
| 98 | + }), |
| 99 | + managedLoginVersion: ManagedLoginVersion.NEWER_MANAGED_LOGIN, |
| 100 | + }); |
| 101 | + |
| 102 | + if (hostedZone) { |
| 103 | + new CnameRecord(this, 'CognitoDomainRecord', { |
| 104 | + zone: hostedZone, |
| 105 | + recordName: subDomain, |
| 106 | + domainName: domain.cloudFrontEndpoint, |
| 107 | + }); |
| 108 | + } |
| 109 | + |
| 110 | + new CfnManagedLoginBranding(this, 'Branding', { |
| 111 | + userPoolId: this.userPool.userPoolId, |
| 112 | + clientId: client.userPoolClientId, |
| 113 | + useCognitoProvidedValues: true, |
| 114 | + }); |
| 115 | + |
| 116 | + new CfnOutput(this, 'UserPoolId', { value: userPool.userPoolId }); |
| 117 | + new CfnOutput(this, 'UserPoolClientId', { value: client.userPoolClientId }); |
| 118 | + } |
| 119 | + |
| 120 | + public addAllowedCallbackUrls(callbackUrl: string, logoutUrl: string) { |
| 121 | + const resource = this.client.node.defaultChild; |
| 122 | + if (!CfnResource.isCfnResource(resource)) { |
| 123 | + throw new Error('Expected CfnResource'); |
| 124 | + } |
| 125 | + resource.addPropertyOverride(`CallbackURLs.${this.callbackUrlCount}`, callbackUrl); |
| 126 | + resource.addPropertyOverride(`LogoutURLs.${this.callbackUrlCount}`, logoutUrl); |
| 127 | + this.callbackUrlCount += 1; |
| 128 | + } |
| 129 | + |
| 130 | + public updateAllowedCallbackUrls(callbackUrls: string[], logoutUrls: string[]) { |
| 131 | + // Lambda depends on userPoolClientId but userPoolClient depends on the CloudFront domain name (callback URL) which depends on Lambda (fURL). |
| 132 | + // To avoid the circular dependency, we update the callback URL after a userPoolClientId is created. |
| 133 | + // We only use this when custom domain is not used. |
| 134 | + new AwsCustomResource(this, 'UpdateCallbackUrls', { |
| 135 | + onUpdate: { |
| 136 | + service: '@aws-sdk/client-cognito-identity-provider', |
| 137 | + action: 'updateUserPoolClient', |
| 138 | + parameters: { |
| 139 | + ClientId: this.client.userPoolClientId, |
| 140 | + UserPoolId: this.userPool.userPoolId, |
| 141 | + AllowedOAuthFlows: ['code'], |
| 142 | + AllowedOAuthFlowsUserPoolClient: true, |
| 143 | + AllowedOAuthScopes: ['profile', 'phone', 'email', 'openid', 'aws.cognito.signin.user.admin'], |
| 144 | + ExplicitAuthFlows: ['ALLOW_USER_PASSWORD_AUTH', 'ALLOW_USER_SRP_AUTH', 'ALLOW_REFRESH_TOKEN_AUTH'], |
| 145 | + CallbackURLs: callbackUrls, |
| 146 | + LogoutURLs: logoutUrls, |
| 147 | + SupportedIdentityProviders: ['COGNITO'], |
| 148 | + TokenValidityUnits: { |
| 149 | + IdToken: 'minutes', |
| 150 | + }, |
| 151 | + IdTokenValidity: 1440, |
| 152 | + }, |
| 153 | + physicalResourceId: PhysicalResourceId.of(this.userPool.userPoolId), |
| 154 | + }, |
| 155 | + policy: AwsCustomResourcePolicy.fromSdkCalls({ |
| 156 | + resources: [this.userPool.userPoolArn], |
| 157 | + }), |
| 158 | + }); |
| 159 | + } |
| 160 | +} |
0 commit comments