AWS Lambda@Edge function for authentication and authorization with Amazon CloudFront.
- Client IP restrictions in whitelist
- Basic authentication on denied Client IP
- Authentication file uses s3 object
Install the required tools.
- sam-local-cli
- Node.js 12+
- Yarn
Execute the command at the project root.
yarn install # or npm install
Environment variables cannot be used with Lambda@Edge, so embed them at build time.
Below is an example.
export ALLOWED_CIDR_BLOCKS=10.25.0.0/8,192.168.11.0/24
export AUTH_FILE_S3_BUCKET=your-s3-bucket
export AUTH_FILE_S3_PREFIX=cf-auth/htpasswd/
yarn build
name | description | default | example |
---|---|---|---|
ALLOWED_CIDR_BLOCKS | アクセスを許可する IP アドレスの範囲を示す CIDR ブロック。カンマ区切りで複数指定可能。 | '127.0.0.1/32' | '10.5.0.0/16, 172.43.16.0/21' |
AUTH_FILE_S3_BUCKET | 認証ファイルが格納されている S3 バケット。未指定の場合は IP アドレス制限のみ行う。 | '' | 'my-cf-auth-bucket' |
AUTH_FILE_S3_PREFIX | 認証ファイルが格納されている S3 バケットのプレフィクス。先頭にスラッシュを付けてはいけない。末尾スラッシュはあってもなくても可(ありに正規化される)。 | '' | 'cloudfront/htpasswd/' |
AUTH_CHAIN_STRATEGY | IP 制限 OR Basic 認証なのか、IP 制限 AND Basic 認証なのかを選択。許可される値は or もしくは and (大文字小文字区別なし)。 |
'or' | 'And' |
AUTH_FILE_CACHE_TTL | 認証ファイルのディスクキャッシュ生存期間(秒)。0 は無期限, 0 未満はキャッシュ無効。Lambda 関数の /tmp ディレクトリを利用する。 |
'60' | '300', '-1' |
The content of the file is a plaintext password.
Place a file with a plaintext password in s3 for each user by host name.
your-s3-bucket
└ your-s3-prefix
├ example.com
│ ├ user1
│ ├ user2
│ └ user3 ...
├ test.com
│ └ user4 ...
└ ...
Edit samconfig.toml for your environment.
cp samconfig.example.toml samconfig.toml
$EDITOR samconfig.toml
Edit template.yml
if you need more customization.
Be sure to deploy to us-east-1
region.
sam deploy --region us-east-1
Associate Lambda@Edge function to CloudFront distribution's viewer-request
using the management console or aws cli.
Unit test
yarn test
Integration test
export AWS_ACCESS_KEY_ID=xxxxxxxxxxxxxxx
export AWS_SECRET_ACCESS_KEY=xxxxxxxxxxxxxxx
export AUTH_FILE_S3_BUCKET=your-s3-bucket
export AUTH_FILE_S3_PREFIX=test/cf-auth/htpasswd/
yarn integ-test