CloudFrontにTerraformを使ってベーシック認証を設定する

概要

CloudFrontにもCloudFront Functionを使うことでベーシック認証を設定することが可能です。
Terraformでその書き方をメモしておきます

Terraform

まず、CloudFront Functionを定義します。

resource "aws_cloudfront_function" "basic-auth" {
  code    = <<-EOT
        function handler(event) {
            var request = event.request;
            var headers = request.headers;
            var cookies = request.cookies;

            // Basic認証情報
            // echo -n hoge:password | base64
            var authString = "Basic aG9nZTpwYXNzd29yZA==";
            if (
              typeof headers.authorization === "undefined" ||
              headers.authorization.value !== authString
            ) {
              return {
                statusCode: 401,
                statusDescription: "Unauthorized",
                headers: { "www-authenticate": { value: "Basic" } }
              };
            }
            return request;
        }
    EOT
  name    = "inamuu-basicAuth"
  runtime = "cloudfront-js-1.0"
}

次に、CloudFrontのビヘイビアで設定します。
パス単位なら、orderedで設定し、全体に設定する場合はdefault cache behaviorで設定します。

resource "aws_cloudfront_distribution" "inamuu-TEST01" {

〜省略〜

  default_cache_behavior {
    allowed_methods  = ["DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT"]
    cached_methods   = ["GET", "HEAD"]
    target_origin_id = "alb-test"

    ### BasicAuth
    function_association {
      event_type   = "viewer-request"
      function_arn = aws_cloudfront_function.basic-auth.arn
    }
  }
}