Skip to main content

CloudFront with Cognito authentication using Lambda@Edge

Project description

cloudcomponents Logo

@cloudcomponents/cdk-cloudfront-authorization

Build Status cdkdx typescript python

CloudFront with Cognito authentication using Lambda@Edge

This construct is based on https://github.com/aws-samples/cloudfront-authorization-at-edge.

Install

TypeScript/JavaScript:

npm i @cloudcomponents/cdk-cloudfront-authorization

Python:

pip install cloudcomponents.cdk-cloudfront-authorization

How to use SPA

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
from aws_cdk.core import Construct, Stack, StackProps
from aws_cdk.aws_cognito import UserPool
from cloudcomponents.cdk_cloudfront_authorization import SpaAuthorization, SpaDistribution

class CloudFrontAuthorizationStack(Stack):
    def __init__(self, scope, id, *, description=None, env=None, stackName=None, tags=None, synthesizer=None, terminationProtection=None, analyticsReporting=None):
        super().__init__(scope, id, description=description, env=env, stackName=stackName, tags=tags, synthesizer=synthesizer, terminationProtection=terminationProtection, analyticsReporting=analyticsReporting)

        user_pool = UserPool(self, "UserPool",
            self_sign_up_enabled=False,
            user_pool_name="cloudfront-authorization-userpool"
        )

        # UserPool must have a domain!
        user_pool.add_domain("Domain",
            cognito_domain=CognitoDomainOptions(
                domain_prefix="cloudcomponents"
            )
        )

        authorization = SpaAuthorization(self, "Authorization",
            user_pool=user_pool
        )

        SpaDistribution(self, "Distribution",
            authorization=authorization
        )

How to use StaticSite

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
from aws_cdk.core import Construct, Stack, StackProps
from aws_cdk.aws_cognito import UserPool
from cloudcomponents.cdk_cloudfront_authorization import StaticSiteAuthorization, StaticSiteDistribution

class CloudFrontAuthorizationStack(Stack):
    def __init__(self, scope, id, *, description=None, env=None, stackName=None, tags=None, synthesizer=None, terminationProtection=None, analyticsReporting=None):
        super().__init__(scope, id, description=description, env=env, stackName=stackName, tags=tags, synthesizer=synthesizer, terminationProtection=terminationProtection, analyticsReporting=analyticsReporting)

        user_pool = UserPool(self, "UserPool",
            self_sign_up_enabled=False,
            user_pool_name="cloudfront-authorization-userpool"
        )

        # UserPool must have a domain!
        user_pool.add_domain("Domain",
            cognito_domain=CognitoDomainOptions(
                domain_prefix="cloudcomponents"
            )
        )

        authorization = StaticSiteAuthorization(self, "Authorization",
            user_pool=user_pool
        )

        StaticSiteDistribution(self, "Distribution",
            authorization=authorization
        )

Legacy CloudFrontWebDistribution

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
from aws_cdk.aws_cloudfront import CloudFrontWebDistribution, OriginAccessIdentity
from aws_cdk.aws_cognito import UserPool
from aws_cdk.core import Construct, Stack, StackProps
from cloudcomponents.cdk_cloudfront_authorization import SpaAuthorization
from cloudcomponents.cdk_deletable_bucket import DeletableBucket

class CloudFrontAuthorizationStack(Stack):
    def __init__(self, scope, id, *, description=None, env=None, stackName=None, tags=None, synthesizer=None, terminationProtection=None, analyticsReporting=None):
        super().__init__(scope, id, description=description, env=env, stackName=stackName, tags=tags, synthesizer=synthesizer, terminationProtection=terminationProtection, analyticsReporting=analyticsReporting)

        user_pool = UserPool(self, "UserPool",
            self_sign_up_enabled=False,
            user_pool_name="cloudfront-authorization-userpool"
        )

        user_pool.add_domain("Domain",
            cognito_domain=CognitoDomainOptions(
                domain_prefix="cloudcomponents"
            )
        )

        authorization = SpaAuthorization(self, "Authorization",
            user_pool=user_pool
        )

        bucket = DeletableBucket(self, "Bucket",
            force_delete=True
        )

        origin_access_identity = OriginAccessIdentity(self, "OriginAccessIdentity",
            comment=f"CloudFront OriginAccessIdentity for {bucket.bucketName}"
        )

        CloudFrontWebDistribution(self, "Distribution",
            origin_configs=[SourceConfiguration(
                s3_origin_source=S3OriginConfig(
                    s3_bucket_source=bucket,
                    origin_access_identity=origin_access_identity
                ),
                behaviors=[authorization.create_legacy_default_behavior(), (SpreadElement ...authorization.createLegacyAdditionalBehaviors()
                  authorization.create_legacy_additional_behaviors())]
            )
            ]
        )

SPA mode vs. Static Site mode

SPA

  • User Pool client does not use a client secret
  • The cookies with JWT's are not "http only", so that they can be read and used by the SPA (e.g. to display the user name, or to refresh tokens)
  • 404's (page not found on S3) will return index.html, to enable SPA-routing

Static Site

  • Enforce use of a client secret
  • Set cookies to be http only by default (unless you've provided other cookie settings explicitly)
  • No special error handling

API Reference

See API.md.

Example

See more complete examples.

License

MIT

Project details


Release history Release notifications | RSS feed

This version

1.2.0

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

File details

Details for the file cloudcomponents.cdk-cloudfront-authorization-1.2.0.tar.gz.

File metadata

  • Download URL: cloudcomponents.cdk-cloudfront-authorization-1.2.0.tar.gz
  • Upload date:
  • Size: 1.0 MB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.2.0 pkginfo/1.5.0.1 requests/2.24.0 setuptools/49.2.0 requests-toolbelt/0.9.1 tqdm/4.48.2 CPython/3.8.5

File hashes

Hashes for cloudcomponents.cdk-cloudfront-authorization-1.2.0.tar.gz
Algorithm Hash digest
SHA256 12facae5ac210b9e912a186e4566add430c89a31905a5863f1d4dcfaf5e30a37
MD5 23141e89cb37b7276abc0e71eb3af402
BLAKE2b-256 7eb4ee81fc01f308874eefdf4ed1225df7ff513b517094ec85588a21de807bf5

See more details on using hashes here.

File details

Details for the file cloudcomponents.cdk_cloudfront_authorization-1.2.0-py3-none-any.whl.

File metadata

File hashes

Hashes for cloudcomponents.cdk_cloudfront_authorization-1.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 9bc1c8e46d66df1d9ef8b7550967445afa577d82472c824063180e7a102b6b98
MD5 f961ef7bbca5343c96085ccdce17b25e
BLAKE2b-256 d803950a115568842622531c4cdadb859739a28f44b84ff2745c13fe07b3a727

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page