cn-terraform / terraform-aws-s3-static-website

Terraform Module for AWS to host Static Website on S3
https://registry.terraform.io/modules/cn-terraform/s3-static-website/aws
Apache License 2.0
20 stars 33 forks source link

Added support for associating a CloudFront function to default cache behavior #26

Closed bendubuisson closed 2 years ago

bendubuisson commented 2 years ago

It's all in the title. Any question let me know.

The actual CloudFront function can be added as following (eg to add Basic Auth):

resource "aws_cloudfront_function" "basic_auth" {
  name    = "basic_auth"
  runtime = "cloudfront-js-1.0"
  comment = "Adds Basic Auth"
  publish = true
  code    = file("basic_auth.js")
}

An example for a simple basic auth function could be:

function handler(event) {
  var authHeaders = event.request.headers.authorization;

  // The Base64-encoded Auth string that should be present.
  // It is an encoding of `Basic base64([username]:[password])`
  // The username and password are:
  //      Username: john
  //      Password: foobar
  var expected = "Basic am9objpmb29iYXI=";

  // If an Authorization header is supplied and it's an exact match, pass the
  // request on through to CF/the origin without any modification.
  if (authHeaders && authHeaders.value === expected) {
    return event.request;
  }

  // But if we get here, we must either be missing the auth header or the
  // credentials failed to match what we expected.
  // Request the browser present the Basic Auth dialog.
  var response = {
    statusCode: 401,
    statusDescription: "Unauthorized",
    headers: {
      "www-authenticate": {
        value: 'Basic realm="Enter credentials for this super secure site"',
      },
    },
  };

  return response;
}

(from https://www.joshualyman.com/2022/01/add-http-basic-authentication-to-cloudfront-distributions/#hooking-up-the-function)