darthhaider
darthhaider

Reputation: 23

CDK How to use the default generated Cloudfront Distribution URL in Cognito Callback URL?

I'm setting up a CloudFront distribution to a static hosted website in S3. For authentication I'm using the Cognito user pool hosted UI for authentication. I want to use the CloudFront Distribution domain name and assign it to the Cognito Callback URL for login. However I'm unable to use the CloudFront Distribution Domain Name that is randomly generated and associate it to the Callback URL since it is instantiated at creation. The only work around I can see is creating a certificate for the CloudFront distribution. This does not work for me since my solution is required to use the CloudFront Distribution Domain Name. How would you solve this issue? Here is my code:

   cd = cloudfront.Distribution(self, "myDist",
        default_root_object='index.html',
        default_behavior=cloudfront.BehaviorOptions(
            origin=origins.S3Origin(website_bucket, origin_access_identity=oai), 
            viewer_protocol_policy=cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS)
    )

    pool = cognito.UserPool(self, 
    "pool",
    user_invitation=cognito.UserInvitationConfig(
        email_subject="Invite to join our awesome app!",
        email_body="Hello {username}, you have been invited to join our awesome app! Your temporary password is {####}",
        sms_message="Hello {username}, your temporary password for our awesome app is {####}"
    ),
    mfa=cognito.Mfa.REQUIRED,
    mfa_second_factor=cognito.MfaSecondFactor(
        sms=True,
        otp=True
    ),
    sign_in_aliases=cognito.SignInAliases(
            username=True,
            email=True
        )
    )

    pool.add_client("app-client",
    o_auth=cognito.OAuthSettings(
        flows=cognito.OAuthFlows(
            authorization_code_grant=True,
            implicit_code_grant=True
        ),
        scopes=[cognito.OAuthScope.OPENID],
        callback_urls=[str(cd.domain_name)],
        logout_urls=["https://my-app-domain.com/signin"]
        )
    )

Upvotes: 0

Views: 1182

Answers (1)

fedonev
fedonev

Reputation: 25709

Simply use cd.domain_name, without casting to str. In your Python code cd.domain_name is a string Token value. The CDK will translate the Token into a CloudFormation ref instrinsic function at synth-time*. CloudFormation handles the value resolution at deploy-time.

If the callback_urls parameter requires a protocol prefix, you can either use Python string interpolation or, if CDK's automagic parsing fails (rare), explicitly pass the required CloudFormation intrinsic function:

# CDK will turn this into a Join and Ref intrinsic function
callback_urls=[f'https://{cd.domain_name}'],

# Is equivalent To:
callback_urls=[Fn.join('', ['https://', cd.domain_name])],

* You can verify this by inspecting the CloudFormation template created in the cdk.out directory when you run cdk synth.

Upvotes: 1

Related Questions