

# Restrict access to an AWS origin
<a name="private-content-restricting-access-to-origin"></a>

You can configure CloudFront and some AWS origins in a way that provides the following benefits:
+ Restricts access to the AWS origin so that it's not publicly accessible.
+ Makes sure that viewers (users) can access the content in the AWS origin only through the specified CloudFront distribution. This prevents viewers from accessing the content directly from the origin, or through an unintended CloudFront distribution.

To do this, configure CloudFront to send authenticated requests to your AWS origin, and configure the AWS origin to only allow access to authenticated requests from CloudFront. For more information, see following topics for compatible types of AWS origins.

**Topics**
+ [Restrict access to an AWS Elemental MediaPackage v2 origin](private-content-restricting-access-to-mediapackage.md)
+ [Restrict access to an AWS Elemental MediaStore origin](private-content-restricting-access-to-mediastore.md)
+ [Restrict access to an AWS Lambda function URL origin](private-content-restricting-access-to-lambda.md)
+ [Restrict access to an Amazon S3 origin](private-content-restricting-access-to-s3.md)
+ [Restrict access with VPC origins](private-content-vpc-origins.md)
+ [Restrict access to an Amazon S3 Multi-Region Access Point origin](private-content-restricting-access-to-s3-mrap.md)

# Restrict access to an AWS Elemental MediaPackage v2 origin
<a name="private-content-restricting-access-to-mediapackage"></a>

CloudFront provides *origin access control* (OAC) for restricting access to a MediaPackage v2 origin.

**Note**  
CloudFront OAC only supports MediaPackage v2. MediaPackage v1 isn't supported.

**Topics**
+ [Creating a new OAC](#create-oac-overview-mediapackage)
+ [Advanced settings for origin access control](#oac-advanced-settings-mediapackage)

## Creating a new OAC
<a name="create-oac-overview-mediapackage"></a>

Complete the steps described in the following topics to set up a new OAC in CloudFront.

**Topics**
+ [Prerequisites](#oac-prerequisites-mediapackage)
+ [Grant CloudFront permission to access the MediaPackage v2 origin](#oac-permission-to-access-mediapackage)
+ [Creating the OAC](#create-oac-mediapackage)

### Prerequisites
<a name="oac-prerequisites-mediapackage"></a>

Before you create and set up OAC, you must have a CloudFront distribution with a MediaPackage v2 origin. For more information, see [Use a MediaStore container or a MediaPackage channel](DownloadDistS3AndCustomOrigins.md#concept_AWS_Media).

### Grant CloudFront permission to access the MediaPackage v2 origin
<a name="oac-permission-to-access-mediapackage"></a>

Before you create an OAC or set it up in a CloudFront distribution, make sure that CloudFront has permission to access the MediaPackage v2 origin. Do this after you create a CloudFront distribution, but before you add the OAC to the MediaPackage v2 origin in the distribution configuration.

Use an IAM policy to allow the CloudFront service principal (`cloudfront.amazonaws.com`) to access the origin. The `Condition` element in the policy allows CloudFront to access the MediaPackage v2 origin *only* when the request is on behalf of the CloudFront distribution that contains the MediaPackage v2 origin. This is the distribution with the MediaPackage v2 origin that you want to add OAC to.

**Example : IAM policy that allows read-only access for a CloudFront distribution with OAC enabled**  
The following policy allows the CloudFront distribution (`E1PDK09ESKHJWT`) access to the MediaPackage v2 origin. The origin is the ARN specified for the `Resource` element.    
****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "AllowCloudFrontServicePrincipal",
            "Effect": "Allow",
            "Principal": {"Service": "cloudfront.amazonaws.com"},
            "Action": "mediapackagev2:GetObject",
            "Resource": "arn:aws:mediapackagev2:us-east-1:123456789012:channelGroup/channel-group-name/channel/channel-name/originEndpoint/origin_endpoint_name",
            "Condition": {
                "StringEquals": {"AWS:SourceArn": "arn:aws:cloudfront::123456789012:distribution/E1PDK09ESKHJWT"}
            }
        }
    ]
}
```

**Notes**  
If you enabled the MQAR feature and origin access control (OAC), add the `mediapackagev2:GetHeadObject` action to the IAM policy. MQAR requires this permission to send `HEAD` requests to the MediaPackage v2 origin. For more information about MQAR, see [Media quality-aware resiliency](media-quality-score.md).
If you create a distribution that doesn't have permission to your MediaPackage v2 origin, you can choose **Copy policy** from the CloudFront console and then choose **Update endpoint permissions**. You can then attach the copied permission to the endpoint. For more information, see [Endpoint policy fields](https://docs.aws.amazon.com/mediapackage/latest/userguide/endpoints-policy.html) in the *AWS Elemental MediaPackage User Guide*. 

### Creating the OAC
<a name="create-oac-mediapackage"></a>

To create an OAC, you can use the AWS Management Console, CloudFormation, the AWS CLI, or the CloudFront API.

------
#### [ Console ]

**To create an OAC**

1. Sign in to the AWS Management Console and open the CloudFront console at [https://console.aws.amazon.com/cloudfront/v4/home](https://console.aws.amazon.com/cloudfront/v4/home).

1. In the navigation pane, choose **Origin access**.

1. Choose **Create control setting**.

1. On the **Create new OAC** form, do the following:

   1. Enter a **Name** and (optionally) a **Description** for the OAC.

   1. For **Signing behavior**, we recommend that you leave the default setting (**Sign requests (recommended)**). For more information, see [Advanced settings for origin access control](#oac-advanced-settings-mediapackage).

1. For **Origin type**, choose **MediaPackage V2**. 

1. Choose **Create**.
**Tip**  
After you create the OAC, make note of the **Name**. You need this in the following procedure.

**To add an OAC to a MediaPackage v2 origin in a distribution**

1. Open the CloudFront console at [https://console.aws.amazon.com/cloudfront/v4/home](https://console.aws.amazon.com/cloudfront/v4/home).

1. Choose a distribution with a MediaPackage V2 origin that you want to add the OAC to, then choose the **Origins** tab.

1. Select the MediaPackage v2 origin that you want to add the OAC to, then choose **Edit**.

1. Select **HTTPS only** for your origin's **Protocol**.

1. From the **Origin access control** dropdown, choose the OAC name that you want to use.

1. Choose **Save changes**.

The distribution starts deploying to all of the CloudFront edge locations. When an edge location receives the new configuration, it signs all requests that it sends to the MediaPackage v2 origin.

------
#### [ CloudFormation ]

To create an OAC with CloudFormation, use the `AWS::CloudFront::OriginAccessControl` resource type. The following example shows the CloudFormation template syntax, in YAML format, for creating an OAC.

```
Type: AWS::CloudFront::OriginAccessControl
Properties: 
  OriginAccessControlConfig: 
      Description: An optional description for the origin access control
      Name: ExampleOAC
      OriginAccessControlOriginType: mediapackagev2
      SigningBehavior: always
      SigningProtocol: sigv4
```

For more information, see [AWS::CloudFront::OriginAccessControl](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cloudfront-originaccesscontrol.html) in the *AWS CloudFormation User Guide*.

------
#### [ CLI ]

To create an origin access control with the AWS Command Line Interface (AWS CLI), use the **aws cloudfront create-origin-access-control** command. You can use an input file to provide the input parameters for the command, rather than specifying each individual parameter as command line input.

**To create an origin access control (CLI with input file)**

1. Use the following command to create a file that's named `origin-access-control.yaml`. This file contains all of the input parameters for the **create-origin-access-control** command.

   ```
   aws cloudfront create-origin-access-control --generate-cli-skeleton yaml-input > origin-access-control.yaml
   ```

1. Open the `origin-access-control.yaml` file that you just created. Edit the file to add a name for the OAC, a description (optional), and change the `SigningBehavior` to `always`. Then save the file.

   For information about other OAC settings, see [Advanced settings for origin access control](#oac-advanced-settings-mediapackage).

1. Use the following command to create the origin access control using the input parameters from the `origin-access-control.yaml` file.

   ```
   aws cloudfront create-origin-access-control --cli-input-yaml file://origin-access-control.yaml
   ```

   Make note of the `Id` value in the command output. You need it to add the OAC to a MediaPackage v2 origin in a CloudFront distribution.

**To attach an OAC to a MediaPackage v2 origin in an existing distribution (CLI with input file)**

1. Use the following command to save the distribution configuration for the CloudFront distribution that you want to add the OAC to. The distribution must have a MediaPackage v2 origin.

   ```
   aws cloudfront get-distribution-config --id <CloudFront distribution ID> --output yaml > dist-config.yaml
   ```

1. Open the file that's named `dist-config.yaml` that you just created. Edit the file, making the following changes:
   + In the `Origins` object, add the OAC's ID to the field that's named `OriginAccessControlId`.
   + Remove the value from the field that's named `OriginAccessIdentity`, if one exists.
   + Rename the `ETag` field to `IfMatch`, but don't change the field's value.

   Save the file when finished.

1. Use the following command to update the distribution to use the origin access control.

   ```
   aws cloudfront update-distribution --id <CloudFront distribution ID> --cli-input-yaml file://dist-config.yaml
   ```

The distribution starts deploying to all of the CloudFront edge locations. When an edge location receives the new configuration, it signs all requests that it sends to the MediaPackage v2 origin.

------
#### [ API ]

To create an OAC with the CloudFront API, use [CreateOriginAccessControl](https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_CreateOriginAccessControl.html). For more information about the fields that you specify in this API call, see the API reference documentation for your AWS SDK or other API client.

After you create an OAC you can attach it to a MediaPackage v2 origin in a distribution, using one of the following API calls:
+ To attach it to an existing distribution, use [UpdateDistribution](https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_UpdateDistribution.html).
+ To attach it to a new distribution, use [CreateDistribution](https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_CreateDistribution.html).

For both of these API calls, provide the OAC ID in the `OriginAccessControlId` field, inside an origin. For more information about the other fields that you specify in these API calls, see [All distribution settings reference](distribution-web-values-specify.md) and the API reference documentation for your AWS SDK or other API client.

------

## Advanced settings for origin access control
<a name="oac-advanced-settings-mediapackage"></a>

The CloudFront OAC feature includes advanced settings that are intended only for specific use cases. Use the recommended settings unless you have a specific need for the advanced settings.

OAC contains a setting named **Signing behavior** (in the console), or `SigningBehavior` (in the API, CLI, and CloudFormation). This setting provides the following options:

**Always sign origin requests (recommended setting)**  
We recommend using this setting, named **Sign requests (recommended)** in the console, or `always` in the API, CLI, and CloudFormation. With this setting, CloudFront always signs all requests that it sends to the MediaPackage v2 origin.

**Never sign origin requests**  
This setting is named **Do not sign requests** in the console, or `never` in the API, CLI, and CloudFormation. Use this setting to turn off OAC for all origins in all distributions that use this OAC. This can save time and effort compared to removing an OAC from all origins and distributions that use it, one by one. With this setting, CloudFront doesn't sign any requests that it sends to the MediaPackage v2 origin.  
To use this setting, the MediaPackage v2 origin must be publicly accessible. If you use this setting with a MediaPackage v2 origin that's not publicly accessible, CloudFront can't access the origin. The MediaPackage v2 origin returns errors to CloudFront and CloudFront passes those errors on to viewers. For more information, see the example MediaPackage v2 policy for [Policies and Permissions in MediaPackage](https://docs.aws.amazon.com/mediapackage/latest/userguide/policies-permissions.html) in the *AWS Elemental MediaPackage User Guide*.

**Don't override the viewer (client) `Authorization` header**  
This setting is named **Do not override authorization header** in the console, or `no-override` in the API, CLI, and CloudFormation. Use this setting when you want CloudFront to sign origin requests only when the corresponding viewer request does not include an `Authorization` header. With this setting, CloudFront passes on the `Authorization` header from the viewer request when one is present, but signs the origin request (adding its own `Authorization` header) when the viewer request doesn't include an `Authorization` header.  
To pass along the `Authorization` header from the viewer request, you *must* add the `Authorization` header to a [cache policy](controlling-the-cache-key.md) for all cache behaviors that use MediaPackage v2 origins associated with this origin access control.

# Restrict access to an AWS Elemental MediaStore origin
<a name="private-content-restricting-access-to-mediastore"></a>

CloudFront provides *origin access control* (OAC) for restricting access to an AWS Elemental MediaStore origin.

**Topics**
+ [Create a new origin access control](#create-oac-overview-mediastore)
+ [Advanced settings for origin access control](#oac-advanced-settings-mediastore)

## Create a new origin access control
<a name="create-oac-overview-mediastore"></a>

Complete the steps described in the following topics to set up a new origin access control in CloudFront.

**Topics**
+ [Prerequisites](#oac-prerequisites-mediastore)
+ [Grant CloudFront permission to access the MediaStore origin](#oac-permission-to-access-mediastore)
+ [Create the origin access control](#create-oac-mediastore)

### Prerequisites
<a name="oac-prerequisites-mediastore"></a>

Before you create and set up origin access control, you must have a CloudFront distribution with a MediaStore origin. 

### Grant CloudFront permission to access the MediaStore origin
<a name="oac-permission-to-access-mediastore"></a>

Before you create an origin access control or set it up in a CloudFront distribution, make sure that CloudFront has permission to access the MediaStore origin. Do this after creating a CloudFront distribution, but before adding the OAC to the MediaStore origin in the distribution configuration. 

Use a MediaStore container policy to allow the CloudFront service principal (`cloudfront.amazonaws.com`) to access the origin. Use a `Condition` element in the policy to allow CloudFront to access the MediaStore container only when the request is on behalf of the CloudFront distribution that contains the MediaStore origin. This is the distribution with the MediaStore origin that you want to add OAC to.

The following are examples of MediaStore container policies that allow a CloudFront distribution to access a MediaStore origin.

**Example MediaStore container policy that allows read-only access for a CloudFront distribution with OAC enabled**    
****  

```
{
        "Version":"2012-10-17",		 	 	 
        "Statement": [
            {
                "Sid": "AllowCloudFrontServicePrincipalReadOnly",
                "Effect": "Allow",
                "Principal": {
                  "Service": "cloudfront.amazonaws.com"
                },
                "Action": [ 
                  "mediastore:GetObject"
                ],
                "Resource": "arn:aws:mediastore:us-east-1:111122223333:container/<container name>/*",
                "Condition": {
                    "StringEquals": {
                      "AWS:SourceArn": "arn:aws:cloudfront::111122223333:distribution/CloudFront-distribution-ID"
                    },
                    "Bool": {
                      "aws:SecureTransport": "true"
                    }
                }
            }
        ]
}
```

**Example MediaStore container policy that allows read and write access for a CloudFront distribution with OAC enabled**    
****  

```
{
        "Version":"2012-10-17",		 	 	 
        "Statement": [
            {
                "Sid": "AllowCloudFrontServicePrincipalReadWrite",
                "Effect": "Allow",
                "Principal": {
                  "Service": "cloudfront.amazonaws.com"
                },
                "Action": [ 
                  "mediastore:GetObject",
                  "mediastore:PutObject"
                ],
                "Resource": "arn:aws:mediastore:us-east-1:111122223333:container/container-name/*",
                "Condition": {
                    "StringEquals": {
                      "AWS:SourceArn": "arn:aws:cloudfront::111122223333:distribution/CloudFront-distribution-ID"
                    },
                    "Bool": {
                      "aws:SecureTransport": "true"
                    }
                }
            }
        ]
}
```

**Note**  
To allow write access, you must configure **Allowed HTTP methods** to include `PUT` in your CloudFront distribution's behavior settings.

### Create the origin access control
<a name="create-oac-mediastore"></a>

To create an OAC, you can use the AWS Management Console, CloudFormation, the AWS CLI, or the CloudFront API.

------
#### [ Console ]

**To create an origin access control**

1. Sign in to the AWS Management Console and open the CloudFront console at [https://console.aws.amazon.com/cloudfront/v4/home](https://console.aws.amazon.com/cloudfront/v4/home).

1. In the navigation pane, choose **Origin access**.

1. Choose **Create control setting**.

1. On the **Create control setting** form, do the following:

   1. In the **Details** pane, enter a **Name** and (optionally) a **Description** for the origin access control.

   1. In the **Settings** pane, we recommend that you leave the default setting (**Sign requests (recommended)**). For more information, see [Advanced settings for origin access control](#oac-advanced-settings-mediastore).

1. Choose MediaStore from the **Origin type** dropdown.

1. Choose **Create**.

   After the OAC is created, make note of the **Name**. You need this in the following procedure.

**To add an origin access control to a MediaStore origin in a distribution**

1. Open the CloudFront console at [https://console.aws.amazon.com/cloudfront/v4/home](https://console.aws.amazon.com/cloudfront/v4/home).

1. Choose a distribution with a MediaStore origin that you want to add the OAC to, then choose the **Origins** tab.

1. Select the MediaStore origin that you want to add the OAC to, then choose **Edit**.

1. Select **HTTPS only** for your origin's **Protocol**.

1. From the **Origin access control** dropdown menu, choose the OAC that you want to use.

1. Choose **Save changes**.

The distribution starts deploying to all of the CloudFront edge locations. When an edge location receives the new configuration, it signs all requests that it sends to the MediaStore bucket origin.

------
#### [ CloudFormation ]

To create an origin access control (OAC) with CloudFormation, use the `AWS::CloudFront::OriginAccessControl` resource type. The following example shows the CloudFormation template syntax, in YAML format, for creating an origin access control.

```
Type: AWS::CloudFront::OriginAccessControl
Properties: 
  OriginAccessControlConfig: 
      Description: An optional description for the origin access control
      Name: ExampleOAC
      OriginAccessControlOriginType: mediastore
      SigningBehavior: always
      SigningProtocol: sigv4
```

For more information, see [AWS::CloudFront::OriginAccessControl](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cloudfront-originaccesscontrol.html) in the *AWS CloudFormation User Guide*.

------
#### [ CLI ]

To create an origin access control with the AWS Command Line Interface (AWS CLI), use the **aws cloudfront create-origin-access-control** command. You can use an input file to provide the input parameters for the command, rather than specifying each individual parameter as command line input.

**To create an origin access control (CLI with input file)**

1. Use the following command to create a file that's named `origin-access-control.yaml`. This file contains all of the input parameters for the **create-origin-access-control** command.

   ```
   aws cloudfront create-origin-access-control --generate-cli-skeleton yaml-input > origin-access-control.yaml
   ```

1. Open the `origin-access-control.yaml` file that you just created. Edit the file to add a name for the OAC, a description (optional), and change the `SigningBehavior` to `always`. Then save the file.

   For information about other OAC settings, see [Advanced settings for origin access control](#oac-advanced-settings-mediastore).

1. Use the following command to create the origin access control using the input parameters from the `origin-access-control.yaml` file.

   ```
   aws cloudfront create-origin-access-control --cli-input-yaml file://origin-access-control.yaml
   ```

   Make note of the `Id` value in the command output. You need it to add the OAC to a MediaStore origin in a CloudFront distribution.

**To attach an OAC to a MediaStore origin in an existing distribution (CLI with input file)**

1. Use the following command to save the distribution configuration for the CloudFront distribution that you want to add the OAC to. The distribution must have a MediaStore origin.

   ```
   aws cloudfront get-distribution-config --id <CloudFront distribution ID> --output yaml > dist-config.yaml
   ```

1. Open the file that's named `dist-config.yaml` that you just created. Edit the file, making the following changes:
   + In the `Origins` object, add the OAC's ID to the field that's named `OriginAccessControlId`.
   + Remove the value from the field that's named `OriginAccessIdentity`, if one exists.
   + Rename the `ETag` field to `IfMatch`, but don't change the field's value.

   Save the file when finished.

1. Use the following command to update the distribution to use the origin access control.

   ```
   aws cloudfront update-distribution --id <CloudFront distribution ID> --cli-input-yaml file://dist-config.yaml
   ```

The distribution starts deploying to all of the CloudFront edge locations. When an edge location receives the new configuration, it signs all requests that it sends to the MediaStore origin.

------
#### [ API ]

To create an origin access control with the CloudFront API, use [CreateOriginAccessControl](https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_CreateOriginAccessControl.html). For more information about the fields that you specify in this API call, see the API reference documentation for your AWS SDK or other API client.

After you create an origin access control you can attach it to a MediaStore origin in a distribution, using one of the following API calls:
+ To attach it to an existing distribution, use [UpdateDistribution](https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_UpdateDistribution.html).
+ To attach it to a new distribution, use [CreateDistribution](https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_CreateDistribution.html).

For both of these API calls, provide the origin access control ID in the `OriginAccessControlId` field, inside an origin. For more information about the other fields that you specify in these API calls, see [All distribution settings reference](distribution-web-values-specify.md) and the API reference documentation for your AWS SDK or other API client.

------

## Advanced settings for origin access control
<a name="oac-advanced-settings-mediastore"></a>

The CloudFront origin access control feature includes advanced settings that are intended only for specific use cases. Use the recommended settings unless you have a specific need for the advanced settings.

Origin access control contains a setting named **Signing behavior** (in the console), or `SigningBehavior` (in the API, CLI, and CloudFormation). This setting provides the following options:

**Always sign origin requests (recommended setting)**  
We recommend using this setting, named **Sign requests (recommended)** in the console, or `always` in the API, CLI, and CloudFormation. With this setting, CloudFront always signs all requests that it sends to the MediaStore origin.

**Never sign origin requests**  
This setting is named **Do not sign requests** in the console, or `never` in the API, CLI, and CloudFormation. Use this setting to turn off origin access control for all origins in all distributions that use this origin access control. This can save time and effort compared to removing an origin access control from all origins and distributions that use it, one by one. With this setting, CloudFront does not sign any requests that it sends to the MediaStore origin.  
To use this setting, the MediaStore origin must be publicly accessible. If you use this setting with a MediaStore origin that's not publicly accessible, CloudFront cannot access the origin. The MediaStore origin returns errors to CloudFront and CloudFront passes those errors on to viewers. For more information, see the example MediaStore container policy for [Public read access over HTTPS](https://docs.aws.amazon.com/mediastore/latest/ug/policies-examples-public-https.html).

**Don't override the viewer (client) `Authorization` header**  
This setting is named **Do not override authorization header** in the console, or `no-override` in the API, CLI, and CloudFormation. Use this setting when you want CloudFront to sign origin requests only when the corresponding viewer request does not include an `Authorization` header. With this setting, CloudFront passes on the `Authorization` header from the viewer request when one is present, but signs the origin request (adding its own `Authorization` header) when the viewer request doesn't include an `Authorization` header.  
To pass along the `Authorization` header from the viewer request, you *must* add the `Authorization` header to a [cache policy](controlling-the-cache-key.md) for all cache behaviors that use MediaStore origins associated with this origin access control.

# Restrict access to an AWS Lambda function URL origin
<a name="private-content-restricting-access-to-lambda"></a>

CloudFront provides *origin access control* (OAC) for restricting access to a Lambda function URL origin.

**Topics**
+ [Create a new OAC](#create-oac-overview-lambda)
+ [Advanced settings for origin access control](#oac-advanced-settings-lambda)
+ [Example template code](#example-template-code-lambda-oac)

## Create a new OAC
<a name="create-oac-overview-lambda"></a>

Complete the steps described in the following topics to set up a new OAC in CloudFront.

**Important**  
If you use `PUT` or `POST` methods with your Lambda function URL, your users must compute the SHA256 of the body and include the payload hash value of the request body in the `x-amz-content-sha256` header when sending the request to CloudFront. Lambda doesn't support unsigned payloads.

**Topics**
+ [Prerequisites](#oac-prerequisites-lambda)
+ [Grant CloudFront permission to access the Lambda function URL](#oac-permission-to-access-lambda)
+ [Create the OAC](#create-oac-lambda)

### Prerequisites
<a name="oac-prerequisites-lambda"></a>

Before you create and set up OAC, you must have a CloudFront distribution with a Lambda function URL as the origin. To use OAC, you must specify `AWS_IAM` as the value for the `AuthType` parameter. For more information, see [Use a Lambda function URL](DownloadDistS3AndCustomOrigins.md#concept_lambda_function_url).

### Grant CloudFront permission to access the Lambda function URL
<a name="oac-permission-to-access-lambda"></a>

Before you create an OAC or set it up in a CloudFront distribution, make sure that CloudFront has permission to access the Lambda function URL. Do this after you create a CloudFront distribution, but before you add the OAC to the Lambda function URL in the distribution configuration.

**Note**  
To update the IAM policy for the Lambda function URL, you must use the AWS Command Line Interface (AWS CLI). Editing the IAM policy in the Lambda console isn't supported at this time.

The following AWS CLI command grants the CloudFront service principal (`cloudfront.amazonaws.com`) access to your Lambda function URL. The `Condition` element in the policy allows CloudFront to access Lambda *only* when the request is on behalf of the CloudFront distribution that contains the Lambda function URL. This is the distribution with the Lambda function URL origin that you want to add OAC to.

**Example : AWS CLI command to update a policy to allow read-only access for a CloudFront distribution with OAC enabled**  
The following AWS CLI commands allows the CloudFront distribution (`E1PDK09ESKHJWT`) access to your Lambda *`FUNCTION_URL_NAME`*.

```
aws lambda add-permission \
--statement-id "AllowCloudFrontServicePrincipal" \
--action "lambda:InvokeFunctionUrl" \
--principal "cloudfront.amazonaws.com" \
--source-arn "arn:aws:cloudfront::123456789012:distribution/E1PDK09ESKHJWT" \
--function-name FUNCTION_URL_NAME
```

```
aws lambda add-permission \
--statement-id "AllowCloudFrontServicePrincipalInvokeFunction" \
--action "lambda:InvokeFunction" \
--principal "cloudfront.amazonaws.com" \
--source-arn "arn:aws:cloudfront::123456789012:distribution/E1PDK09ESKHJWT" \
--function-name FUNCTION_URL_NAME
```

**Note**  
If you create a distribution and it doesn't have permission to your Lambda function URL, you can choose **Copy CLI command** from the CloudFront console, and then enter this command from your command line terminal. For more information, see [Granting function access to AWS services](https://docs.aws.amazon.com/lambda/latest/dg/access-control-resource-based.html#permissions-resource-serviceinvoke) in the *AWS Lambda Developer Guide*. 

### Create the OAC
<a name="create-oac-lambda"></a>

To create an OAC, you can use the AWS Management Console, CloudFormation, the AWS CLI, or the CloudFront API.

------
#### [ Console ]

**To create an OAC**

1. Sign in to the AWS Management Console and open the CloudFront console at [https://console.aws.amazon.com/cloudfront/v4/home](https://console.aws.amazon.com/cloudfront/v4/home).

1. In the navigation pane, choose **Origin access**.

1. Choose **Create control setting**.

1. On the **Create new OAC** form, do the following:

   1. Enter a **Name** and (optionally) a **Description** for the OAC.

   1. For **Signing behavior**, we recommend that you leave the default setting (**Sign requests (recommended)**). For more information, see [Advanced settings for origin access control](#oac-advanced-settings-lambda).

1. For **Origin type**, choose **Lambda**. 

1. Choose **Create**.
**Tip**  
After you create the OAC, make note of the **Name**. You need this in the following procedure.

**To add an origin access control to a Lambda function URL in a distribution**

1. Open the CloudFront console at [https://console.aws.amazon.com/cloudfront/v4/home](https://console.aws.amazon.com/cloudfront/v4/home).

1. Choose a distribution with a Lambda function URL that you want to add the OAC to, then choose the **Origins** tab.

1. Select the Lambda function URL that you want to add the OAC to, and then choose **Edit**.

1. Select **HTTPS only** for your origin's **Protocol**.

1. From the **Origin access control** dropdown, choose the OAC name that you want to use.

1. Choose **Save changes**.

The distribution starts deploying to all of the CloudFront edge locations. When an edge location receives the new configuration, it signs all requests that it sends to the Lambda function URL.

------
#### [ CloudFormation ]

To create an OAC with CloudFormation, use the `AWS::CloudFront::OriginAccessControl` resource type. The following example shows the CloudFormation template syntax, in YAML format, for creating an OAC.

```
Type: AWS::CloudFront::OriginAccessControl
Properties: 
  OriginAccessControlConfig: 
      Description: An optional description for the origin access control
      Name: ExampleOAC
      OriginAccessControlOriginType: lambda
      SigningBehavior: always
      SigningProtocol: sigv4
```

For more information, see [AWS::CloudFront::OriginAccessControl](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cloudfront-originaccesscontrol.html) in the *AWS CloudFormation User Guide*.

------
#### [ CLI ]

To create an origin access control with the AWS Command Line Interface (AWS CLI), use the **aws cloudfront create-origin-access-control** command. You can use an input file to provide the input parameters for the command, rather than specifying each individual parameter as command line input.

**To create an origin access control (CLI with input file)**

1. Use the following command to create a file that's named `origin-access-control.yaml`. This file contains all of the input parameters for the **create-origin-access-control** command.

   ```
   aws cloudfront create-origin-access-control --generate-cli-skeleton yaml-input > origin-access-control.yaml
   ```

1. Open the `origin-access-control.yaml` file that you just created. Edit the file to add a name for the OAC, a description (optional), and change the `SigningBehavior` to `always`. Then save the file.

   For information about other OAC settings, see [Advanced settings for origin access control](#oac-advanced-settings-lambda).

1. Use the following command to create the origin access control using the input parameters from the `origin-access-control.yaml` file.

   ```
   aws cloudfront create-origin-access-control --cli-input-yaml file://origin-access-control.yaml
   ```

   Make note of the `Id` value in the command output. You need it to add the OAC to a Lambda function URL in a CloudFront distribution.

**To attach an OAC to a Lambda function URL in an existing distribution (CLI with input file)**

1. Use the following command to save the distribution configuration for the CloudFront distribution that you want to add the OAC to. The distribution must have a Lambda function URL as the origin.

   ```
   aws cloudfront get-distribution-config --id <CloudFront distribution ID> --output yaml > dist-config.yaml
   ```

1. Open the file that's named `dist-config.yaml` that you just created. Edit the file, making the following changes:
   + In the `Origins` object, add the OAC's ID to the field that's named `OriginAccessControlId`.
   + Remove the value from the field that's named `OriginAccessIdentity`, if one exists.
   + Rename the `ETag` field to `IfMatch`, but don't change the field's value.

   Save the file when finished.

1. Use the following command to update the distribution to use the origin access control.

   ```
   aws cloudfront update-distribution --id <CloudFront distribution ID> --cli-input-yaml file://dist-config.yaml
   ```

The distribution starts deploying to all of the CloudFront edge locations. When an edge location receives the new configuration, it signs all requests that it sends to the Lambda function URL.

------
#### [ API ]

To create an OAC with the CloudFront API, use [CreateOriginAccessControl](https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_CreateOriginAccessControl.html). For more information about the fields that you specify in this API call, see the API reference documentation for your AWS SDK or other API client.

After you create an OAC you can attach it to a Lambda function URL in a distribution, using one of the following API calls:
+ To attach it to an existing distribution, use [UpdateDistribution](https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_UpdateDistribution.html).
+ To attach it to a new distribution, use [CreateDistribution](https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_CreateDistribution.html).

For both of these API calls, provide the OAC ID in the `OriginAccessControlId` field, inside an origin. For more information about the other fields that you specify in these API calls, see and the API reference documentation for your AWS SDK or other API client.

------

## Advanced settings for origin access control
<a name="oac-advanced-settings-lambda"></a>

The CloudFront OAC feature includes advanced settings that are intended only for specific use cases. Use the recommended settings unless you have a specific need for the advanced settings.

OAC contains a setting named **Signing behavior** (in the console), or `SigningBehavior` (in the API, CLI, and CloudFormation). This setting provides the following options:

**Always sign origin requests (recommended setting)**  
We recommend using this setting, named **Sign requests (recommended)** in the console, or `always` in the API, CLI, and CloudFormation. With this setting, CloudFront always signs all requests that it sends to the Lambda function URL.

**Never sign origin requests**  
This setting is named **Do not sign requests** in the console, or `never` in the API, CLI, and CloudFormation. Use this setting to turn off OAC for all origins in all distributions that use this OAC. This can save time and effort compared to removing an OAC from all origins and distributions that use it, one by one. With this setting, CloudFront doesn't sign any requests that it sends to the Lambda function URL.  
To use this setting, the Lambda function URL must be publicly accessible. If you use this setting with a Lambda function URL that's not publicly accessible, CloudFront can't access the origin. The Lambda function URL returns errors to CloudFront and CloudFront passes those errors on to viewers. For more information, see [Security and auth model for Lambda function URLs](https://docs.aws.amazon.com/lambda/latest/dg/urls-auth.html) in the *AWS Lambda User Guide*.

**Don't override the viewer (client) `Authorization` header**  
This setting is named **Do not override authorization header** in the console, or `no-override` in the API, CLI, and CloudFormation. Use this setting when you want CloudFront to sign origin requests only when the corresponding viewer request does not include an `Authorization` header. With this setting, CloudFront passes on the `Authorization` header from the viewer request when one is present, but signs the origin request (adding its own `Authorization` header) when the viewer request doesn't include an `Authorization` header.  
+ If you use this setting, you must specify the Signature Version 4 signing for the Lambda function URL instead of your CloudFront distribution's name or CNAME. When CloudFront forwards the `Authorization` header from the viewer request to the Lambda function URL, Lambda will validate the signature against the host of the Lambda URL domain. If the signature isn't based on the Lambda URL domain, the host in the signature won't match the host used by the Lambda URL origin. This means the request will fail, resulting in a signature validation error.
+ To pass along the `Authorization` header from the viewer request, you *must* add the `Authorization` header to a [cache policy](controlling-the-cache-key.md) for all cache behaviors that use Lambda function URLs associated with this origin access control.

## Example template code
<a name="example-template-code-lambda-oac"></a>

If your CloudFront origin is a Lambda function URL that's associated with an OAC, you can use the following Python script to upload files to the Lambda function with the `POST` method. 

This code assumes that you configured the OAC with the default signing behavior set to **Always sign origin requests** and that you didn't select the **Do not override authorization header** setting.

This configuration allows the OAC to manage SigV4 authorization correctly with Lambda by using the Lambda hostname. The payload is signed by using SigV4 from the IAM identity that's authorized for the Lambda function URL, which is designated as the `IAM_AUTH` type. 

The template demonstrates how to handle signed payload hash values in the x-amz-content-sha256 header for `POST` requests from the client side. Specifically, this template is designed to manage form data payloads. The template enables secure file uploads to a Lambda function URL through CloudFront, and uses AWS authentication mechanisms to ensure that only authorized requests can access the Lambda function.

**The code includes the following functionality:**  
Meets the requirement for including the payload hash in the x-amz-content-sha256 header
Uses SigV4 authentication for secure AWS service access
Supports file uploads by using multi-part form data
Includes error handling for request exceptions

```
import boto3
from botocore.auth import SigV4Auth
from botocore.awsrequest import AWSRequest
import requests
import hashlib
import os


def calculate_body_hash(body):
    return hashlib.sha256(body).hexdigest()


def sign_request(request, credentials, region, service):
    sigv4 = SigV4Auth(credentials, service, region)
    sigv4.add_auth(request)


def upload_file_to_lambda(cloudfront_url, file_path, region):
    # AWS credentials
    session = boto3.Session()
    credentials = session.get_credentials()

    # Prepare the multipart form-data
    boundary = "------------------------boundary"

    # Read file content
    with open(file_path, 'rb') as file:
        file_content = file.read()

    # Get the filename from the path
    filename = os.path.basename(file_path)

    # Prepare the multipart body
    body = (
        f'--{boundary}\r\n'
        f'Content-Disposition: form-data; name="file"; filename="{filename}"\r\n'
        f'Content-Type: application/octet-stream\r\n\r\n'
    ).encode('utf-8')
    body += file_content
    body += f'\r\n--{boundary}--\r\n'.encode('utf-8')

    # Calculate SHA256 hash of the entire body
    body_hash = calculate_body_hash(body)

    # Prepare headers
    headers = {
        'Content-Type': f'multipart/form-data; boundary={boundary}',
        'x-amz-content-sha256': body_hash
    }

    # Create the request
    request = AWSRequest(
        method='POST',
        url=cloudfront_url,
        data=body,
        headers=headers
    )

    # Sign the request
    sign_request(request, credentials, region, 'lambda')

    # Get the signed headers
    signed_headers = dict(request.headers)

    # Print request headers before sending
    print("Request Headers:")
    for header, value in signed_headers.items():
        print(f"{header}: {value}")

    try:
        # Send POST request with signed headers
        response = requests.post(
            cloudfront_url,
            data=body,
            headers=signed_headers
        )

        # Print response status and content
        print(f"\nStatus code: {response.status_code}")
        print("Response:", response.text)

        # Print response headers
        print("\nResponse Headers:")
        for header, value in response.headers.items():
            print(f"{header}: {value}")

    except requests.exceptions.RequestException as e:
        print(f"An error occurred: {e}")


# Usage
cloudfront_url = "https://d111111abcdef8.cloudfront.net"
file_path = r"filepath"
region = "us-east-1"  # example: "us-west-2"

upload_file_to_lambda(cloudfront_url, file_path, region)
```

# Restrict access to an Amazon S3 origin
<a name="private-content-restricting-access-to-s3"></a>

CloudFront provides two ways to send authenticated requests to an Amazon S3 origin: *origin access control* (OAC) and *origin access identity* (OAI). OAC helps you secure your origins, such as Amazon S3. 

We *recommend* that you use OAC instead because it supports the following features:
+ All Amazon S3 buckets in all AWS Regions, including opt-in Regions launched after December 2022
+ Amazon S3 [server-side encryption with AWS KMS](https://docs.aws.amazon.com/AmazonS3/latest/userguide/serv-side-encryption.html) (SSE-KMS)
+ Dynamic requests (`PUT` and `DELETE`) to Amazon S3

OAI doesn't support these features or it requires extra workarounds in those scenarios. If you're already using OAI and want to migrate, see [Migrating from origin access identity (OAI) to origin access control (OAC)](#migrate-from-oai-to-oac).

**Notes**  
When you use CloudFront OAC with Amazon S3 bucket origins, you must set **Amazon S3 Object Ownership** to **Bucket owner enforced**, the default for new Amazon S3 buckets. If you require ACLs, use the **Bucket owner preferred** setting to maintain control over objects uploaded via CloudFront.
If your origin is an Amazon S3 bucket configured as a [website endpoint](https://docs.aws.amazon.com/AmazonS3/latest/userguide/WebsiteEndpoints.html), you must set it up with CloudFront as a custom origin. That means you can't use OAC (or OAI). OAC doesn't support origin redirect by using Lambda@Edge.
If you use an Amazon S3 Multi-Region Access Point as your CloudFront origin, see [Restrict access to an Amazon S3 Multi-Region Access Point origin](private-content-restricting-access-to-s3-mrap.md). S3 Multi-Region Access Points require a different OAC configuration.

The following topics describe how to use OAC with an Amazon S3 origin. 

**Topics**
+ [Create a new origin access control](#create-oac-overview-s3)
+ [Delete a distribution with an OAC attached to an S3 bucket](#delete-oac-distribution-s3)
+ [Migrating from origin access identity (OAI) to origin access control (OAC)](#migrate-from-oai-to-oac)
+ [Advanced settings for origin access control](#oac-advanced-settings-s3)

## Create a new origin access control
<a name="create-oac-overview-s3"></a>

Complete the steps described in the following topics to set up a new origin access control in CloudFront.

**Topics**
+ [Prerequisites](#oac-prerequisites-s3)
+ [Grant CloudFront permission to access the S3 bucket](#oac-permission-to-access-s3)
+ [Create the origin access control](#create-oac-s3)

### Prerequisites
<a name="oac-prerequisites-s3"></a>

Before you create and set up origin access control (OAC), you must have a CloudFront distribution with an Amazon S3 bucket origin. This origin must be a regular S3 bucket, not a bucket configured as a [website endpoint](https://docs.aws.amazon.com/AmazonS3/latest/userguide/WebsiteEndpoints.html). For more information about setting up a CloudFront distribution with an S3 bucket origin, see [Get started with a CloudFront standard distribution](GettingStarted.SimpleDistribution.md).

**Important**  
When you use OAC to secure your Amazon S3 origin, communication between CloudFront and Amazon S3 is *always* through HTTPS, but only when you choose to *always sign requests*. You must choose **Sign requests (recommended)** in the console or specify `always` in the CloudFront API, AWS CLI, or CloudFormation.   
If you choose either the **Do not sign requests** or **Do not override authorization header** option instead, CloudFront uses the connection protocol that you specified in the following policies:  
[Viewer protocol policy](using-https-viewers-to-cloudfront.md) 
[Origin protocol policy](DownloadDistValuesOrigin.md#DownloadDistValuesOriginProtocolPolicy) (custom origins only)
For example, if you choose **Do not override authorization header** and want to use HTTPS between CloudFront and your Amazon S3 origin, use **Redirect HTTP to HTTPS** or **HTTPS only** for the [viewer protocol policy](using-https-viewers-to-cloudfront.md).

### Grant CloudFront permission to access the S3 bucket
<a name="oac-permission-to-access-s3"></a>

Before you create an origin access control (OAC) or set it up in a CloudFront distribution, make sure that CloudFront has permission to access the S3 bucket origin. Do this after creating a CloudFront distribution, but before adding the OAC to the S3 origin in the distribution configuration.

Use an S3 [bucket policy](https://docs.aws.amazon.com/AmazonS3/latest/userguide/bucket-policies.html) to allow the CloudFront service principal (`cloudfront.amazonaws.com`) to access the bucket. Use a `Condition` element in the policy to allow CloudFront to access the bucket only when the request is on behalf of the CloudFront distribution that contains the S3 origin. This is the distribution with the S3 origin that you want to add OAC to.

For information about adding or modifying a bucket policy, see [Adding a bucket policy using the Amazon S3 console](https://docs.aws.amazon.com/AmazonS3/latest/userguide/add-bucket-policy.html) in the *Amazon S3 User Guide*.

The following are examples of S3 bucket policies that allow a CloudFront distribution with OAC enabled access to an S3 origin.

**Example S3 bucket policy that allows read-only access for a CloudFront distribution with OAC enabled**    
****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "AllowCloudFrontServicePrincipalReadOnly",
      "Effect": "Allow",
      "Principal": {
        "Service": "cloudfront.amazonaws.com"
      },
      "Action": "s3:GetObject",
      "Resource": "arn:aws:s3:::amzn-s3-demo-bucket/*",
      "Condition": {
        "StringEquals": {
          "AWS:SourceArn": "arn:aws:cloudfront::111122223333:distribution/<CloudFront distribution ID>"
        }
      }
    }
  ]
}
```

**Example S3 bucket policy that allows read and write access for a CloudFront distribution with OAC enabled**    
****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "AllowCloudFrontServicePrincipalReadWrite",
      "Effect": "Allow",
      "Principal": {
        "Service": "cloudfront.amazonaws.com"
      },
      "Action": [
        "s3:GetObject",
        "s3:PutObject"
      ],
      "Resource": "arn:aws:s3:::amzn-s3-demo-bucket/*",
      "Condition": {
        "StringEquals": {
          "AWS:SourceArn": "arn:aws:cloudfront::111122223333:distribution/CloudFront-distribution-ID>"
        }
      }
    }
  ]
}
```

#### SSE-KMS
<a name="oac-permissions-sse-kms"></a>

If the objects in the S3 bucket origin are encrypted using [server-side encryption with AWS Key Management Service (SSE-KMS)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingKMSEncryption.html), you must make sure that the CloudFront distribution has permission to use the AWS KMS key. To give the CloudFront distribution permission to use the KMS key, add a statement to the [KMS key policy](https://docs.aws.amazon.com/kms/latest/developerguide/key-policies.html). For information about how to modify a key policy, see [Changing a key policy](https://docs.aws.amazon.com/kms/latest/developerguide/key-policy-modifying.html) in the *AWS Key Management Service Developer Guide*.

**Example KMS key policy statement**  
The following example shows a AWS KMS policy statement that allows the CloudFront distribution with OAC to access a KMS key for SSE-KMS.  

```
{
    "Sid": "AllowCloudFrontServicePrincipalSSE-KMS",
    "Effect": "Allow",
    "Principal": {
        "Service": [
            "cloudfront.amazonaws.com"
        ]
     },
    "Action": [
        "kms:Decrypt",
        "kms:Encrypt",
        "kms:GenerateDataKey*"
    ],
    "Resource": "*",
    "Condition": {
            "StringEquals": {
                "AWS:SourceArn": "arn:aws:cloudfront::111122223333:distribution/<CloudFront distribution ID>"
            }
        }
}
```

### Create the origin access control
<a name="create-oac-s3"></a>

To create an origin access control (OAC), you can use the AWS Management Console, CloudFormation, the AWS CLI, or the CloudFront API.

------
#### [ Console ]

**To create an origin access control**

1. Sign in to the AWS Management Console and open the CloudFront console at [https://console.aws.amazon.com/cloudfront/v4/home](https://console.aws.amazon.com/cloudfront/v4/home).

1. In the navigation pane, choose **Origin access**.

1. Choose **Create control setting**.

1. On the **Create control setting** form, do the following:

   1. In the **Details** pane, enter a **Name** and (optionally) a **Description** for the origin access control.

   1. In the **Settings** pane, we recommend that you leave the default setting (**Sign requests (recommended)**). For more information, see [Advanced settings for origin access control](#oac-advanced-settings-s3).

1. Choose S3 from the **Origin type** dropdown.

1. Choose **Create**.

   After the OAC is created, make note of the **Name**. You need this in the following procedure.

**To add an origin access control to an S3 origin in a distribution**

1. Open the CloudFront console at [https://console.aws.amazon.com/cloudfront/v4/home](https://console.aws.amazon.com/cloudfront/v4/home).

1. Choose a distribution with an S3 origin that you want to add the OAC to, then choose the **Origins** tab.

1. Select the S3 origin that you want to add the OAC to, then choose **Edit**.

1. For **Origin access**, choose **Origin access control settings (recommended)**.

1. From the **Origin access control** dropdown menu, choose the OAC that you want to use.

1. Choose **Save changes**.

The distribution starts deploying to all of the CloudFront edge locations. When an edge location receives the new configuration, it signs all requests that it sends to the S3 bucket origin.

------
#### [ CloudFormation ]

To create an origin access control (OAC) with CloudFormation, use the `AWS::CloudFront::OriginAccessControl` resource type. The following example shows the CloudFormation template syntax, in YAML format, for creating an origin access control.

```
Type: AWS::CloudFront::OriginAccessControl
Properties: 
  OriginAccessControlConfig: 
      Description: An optional description for the origin access control
      Name: ExampleOAC
      OriginAccessControlOriginType: s3
      SigningBehavior: always
      SigningProtocol: sigv4
```

For more information, see [AWS::CloudFront::OriginAccessControl](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cloudfront-originaccesscontrol.html) in the *AWS CloudFormation User Guide*.

------
#### [ CLI ]

To create an origin access control with the AWS Command Line Interface (AWS CLI), use the **aws cloudfront create-origin-access-control** command. You can use an input file to provide the input parameters for the command, rather than specifying each individual parameter as command line input.

**To create an origin access control (CLI with input file)**

1. Use the following command to create a file that's named `origin-access-control.yaml`. This file contains all of the input parameters for the **create-origin-access-control** command.

   ```
   aws cloudfront create-origin-access-control --generate-cli-skeleton yaml-input > origin-access-control.yaml
   ```

1. Open the `origin-access-control.yaml` file that you just created. Edit the file to add a name for the OAC, a description (optional), and change the `SigningBehavior` to `always`. Then save the file.

   For information about other OAC settings, see [Advanced settings for origin access control](#oac-advanced-settings-s3).

1. Use the following command to create the origin access control using the input parameters from the `origin-access-control.yaml` file.

   ```
   aws cloudfront create-origin-access-control --cli-input-yaml file://origin-access-control.yaml
   ```

   Make note of the `Id` value in the command output. You need it to add the OAC to an S3 bucket origin in a CloudFront distribution.

**To attach an OAC to an S3 bucket origin in an existing distribution (CLI with input file)**

1. Use the following command to save the distribution configuration for the CloudFront distribution that you want to add the OAC to. The distribution must have an S3 bucket origin.

   ```
   aws cloudfront get-distribution-config --id <CloudFront distribution ID> --output yaml > dist-config.yaml
   ```

1. Open the file that's named `dist-config.yaml` that you just created. Edit the file, making the following changes:
   + In the `Origins` object, add the OAC's ID to the field that's named `OriginAccessControlId`.
   + Remove the value from the field that's named `OriginAccessIdentity`, if one exists.
   + Rename the `ETag` field to `IfMatch`, but don't change the field's value.

   Save the file when finished.

1. Use the following command to update the distribution to use the origin access control.

   ```
   aws cloudfront update-distribution --id <CloudFront distribution ID> --cli-input-yaml file://dist-config.yaml
   ```

The distribution starts deploying to all of the CloudFront edge locations. When an edge location receives the new configuration, it signs all requests that it sends to the S3 bucket origin.

------
#### [ API ]

To create an origin access control with the CloudFront API, use [CreateOriginAccessControl](https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_CreateOriginAccessControl.html). For more information about the fields that you specify in this API call, see the API reference documentation for your AWS SDK or other API client.

After you create an origin access control you can attach it to an S3 bucket origin in a distribution, using one of the following API calls:
+ To attach it to an existing distribution, use [UpdateDistribution](https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_UpdateDistribution.html).
+ To attach it to a new distribution, use [CreateDistribution](https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_CreateDistribution.html).

For both of these API calls, provide the origin access control ID in the `OriginAccessControlId` field, inside an origin. For more information about the other fields that you specify in these API calls, see [All distribution settings reference](distribution-web-values-specify.md) and the API reference documentation for your AWS SDK or other API client.

------

## Delete a distribution with an OAC attached to an S3 bucket
<a name="delete-oac-distribution-s3"></a>

If you need to delete a distribution with an OAC attached to an S3 bucket, you should delete the distribution before you delete the S3 bucket origin. Alternatively, include the Region in the origin domain name. If this isn't possible, you can remove the OAC from the distribution by switching to public before deletion. For more information, see [Delete a distribution](HowToDeleteDistribution.md).

## Migrating from origin access identity (OAI) to origin access control (OAC)
<a name="migrate-from-oai-to-oac"></a>

To migrate from a legacy origin access identity (OAI) to an origin access control (OAC), first update the S3 bucket origin to allow both the OAI and the distribution with OAC enabled to access the bucket's content. This makes sure that CloudFront never loses access to the bucket during the transition. To allow both OAI and the distribution with OAC enabled to access an S3 bucket, update the [bucket policy](https://docs.aws.amazon.com/AmazonS3/latest/userguide/bucket-policies.html) to include two statements, one for each kind of principal.

The following example S3 bucket policy allows both an OAI and a distribution with OAC enabled to access an S3 origin.

**Example S3 bucket policy that allows read-only access for an OAI and a CloudFront distribution with OAC enabled**    
****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "AllowCloudFrontServicePrincipalReadOnly",
            "Effect": "Allow",
            "Principal": {
                "Service": "cloudfront.amazonaws.com"
            },
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::<S3 bucket name>/*",
            "Condition": {
                "StringEquals": {
                    "AWS:SourceArn": "arn:aws:cloudfront::111122223333:distribution/<CloudFront distribution ID>"
                }
            }
        },
        {
            "Sid": "AllowLegacyOAIReadOnly",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity <origin access identity ID>"
            },
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::<S3 bucket name>/*"
        }
    ]
}
```

After you update the S3 origin's bucket policy to allow access to both OAI and OAC, you can update the distribution configuration to use OAC instead of OAI. For more information, see [Create a new origin access control](#create-oac-overview-s3).

After the distribution is fully deployed, you can remove the statement in the bucket policy that allows access to the OAI. For more information, see [Grant CloudFront permission to access the S3 bucket](#oac-permission-to-access-s3).

## Advanced settings for origin access control
<a name="oac-advanced-settings-s3"></a>

The CloudFront origin access control feature includes advanced settings that are intended only for specific use cases. Use the recommended settings unless you have a specific need for the advanced settings.

Origin access control contains a setting named **Signing behavior** (in the console), or `SigningBehavior` (in the API, CLI, and CloudFormation). This setting provides the following options:

**Always sign origin requests (recommended setting)**  
We recommend using this setting, named **Sign requests (recommended)** in the console, or `always` in the API, CLI, and CloudFormation. With this setting, CloudFront always signs all requests that it sends to the S3 bucket origin.

**Never sign origin requests**  
This setting is named **Do not sign requests** in the console, or `never` in the API, CLI, and CloudFormation. Use this setting to turn off origin access control for all origins in all distributions that use this origin access control. This can save time and effort compared to removing an origin access control from all origins and distributions that use it, one by one. With this setting, CloudFront does not sign any requests that it sends to the S3 bucket origin.  
To use this setting, the S3 bucket origin must be publicly accessible. If you use this setting with an S3 bucket origin that's not publicly accessible, CloudFront cannot access the origin. The S3 bucket origin returns errors to CloudFront and CloudFront passes those errors on to viewers.

**Don't override the viewer (client) `Authorization` header**  
This setting is named **Do not override authorization header** in the console, or `no-override` in the API, CLI, and CloudFormation. Use this setting when you want CloudFront to sign origin requests only when the corresponding viewer request does not include an `Authorization` header. With this setting, CloudFront passes on the `Authorization` header from the viewer request when one is present, but signs the origin request (adding its own `Authorization` header) when the viewer request doesn't include an `Authorization` header.  
To pass along the `Authorization` header from the viewer request, you *must* add the `Authorization` header to a [cache policy](controlling-the-cache-key.md) for all cache behaviors that use S3 bucket origins associated with this origin access control.

## Use an origin access identity (legacy, not recommended)
<a name="private-content-restricting-access-to-s3-oai"></a>

### Overview of origin access identity
<a name="private-content-restricting-access-to-s3-overview"></a>

CloudFront *origin access identity* (OAI) provides similar functionality as *origin access control* (OAC), but it doesn't work for all scenarios. Specifically, OAI doesn't support:
+ Amazon S3 buckets in all AWS Regions, including opt-in Regions
+ Amazon S3 [server-side encryption with AWS KMS](https://docs.aws.amazon.com/AmazonS3/latest/userguide/serv-side-encryption.html) (SSE-KMS)
+ Dynamic requests (`PUT`, `POST`, or `DELETE`) to Amazon S3
+ New AWS Regions launched after January 2023

**Tip**  
We recommend that you use OAC instead. To set up OAC, see [Create a new origin access control](#create-oac-overview-s3). For information about how to migrate from OAI to OAC, see [Migrating from origin access identity (OAI) to origin access control (OAC)](#migrate-from-oai-to-oac).

### Give an origin access identity permission to read files in the Amazon S3 bucket
<a name="private-content-granting-permissions-to-oai"></a>

When you create an OAI or add one to a distribution with the CloudFront console, you can automatically update the Amazon S3 bucket policy to give the OAI permission to access your bucket. Alternatively, you can choose to manually create or update the bucket policy. Whichever method you use, you should still review the permissions to make sure that:
+ Your CloudFront OAI can access files in the bucket on behalf of viewers who are requesting them through CloudFront.
+ Viewers can't use Amazon S3 URLs to access your files outside of CloudFront.

**Important**  
If you configure CloudFront to accept and forward all of the HTTP methods that CloudFront supports, make sure you give your CloudFront OAI the desired permissions. For example, if you configure CloudFront to accept and forward requests that use the `DELETE` method, configure your bucket policy to handle `DELETE` requests appropriately so viewers can delete only files that you want them to.

#### Use Amazon S3 bucket policies
<a name="private-content-updating-s3-bucket-policies"></a>

You can give a CloudFront OAI access to files in an Amazon S3 bucket by creating or updating the bucket policy in the following ways:
+ Using the Amazon S3 bucket's **Permissions** tab in the [Amazon S3 console](https://console.aws.amazon.com/s3/home).
+ Using [PutBucketPolicy](https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutBucketPolicy.html) in the Amazon S3 API.
+ Using the [CloudFront console](https://console.aws.amazon.com/cloudfront/v4/home). When you add an OAI to your origin settings in the CloudFront console, you can choose **Yes, update the bucket policy** to tell CloudFront to update the bucket policy on your behalf.

If you update the bucket policy manually, make sure that you:
+ Specify the correct OAI as the `Principal` in the policy.
+ Give the OAI the permissions it needs to access objects on behalf of viewers.

For more information, see the following sections.

##### Specify an OAI as the `Principal` in a bucket policy
<a name="private-content-updating-s3-bucket-policies-principal"></a>

To specify an OAI as the `Principal` in an Amazon S3 bucket policy, use the OAI's Amazon Resource Name (ARN), which includes the OAI's ID. For example:

```
"Principal": {
    "AWS": "arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity <origin access identity ID>"
}
```

Find the OAI ID in the CloudFront console under **Security**, **Origin access**, **Identities (legacy)**. Alternatively, use [ListCloudFrontOriginAccessIdentities](https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_ListCloudFrontOriginAccessIdentities.html) in the CloudFront API.

##### Give permissions to an OAI
<a name="private-content-updating-s3-bucket-policies-permissions"></a>

To give the OAI the permissions to access objects in your Amazon S3 bucket, use actions in the policy that relate to specific Amazon S3 API operations. For example, the `s3:GetObject` action allows the OAI to read objects in the bucket. For more information, see the examples in the following section, or see [Amazon S3 actions](https://docs.aws.amazon.com/AmazonS3/latest/dev/using-with-s3-actions.html) in the *Amazon Simple Storage Service User Guide*.

##### Amazon S3 bucket policy examples
<a name="private-content-updating-s3-bucket-policies-examples"></a>

The following examples show Amazon S3 bucket policies that allow CloudFront OAI to access an S3 bucket.

Find the OAI ID in the CloudFront console under **Security**, **Origin access**, **Identities (legacy)**. Alternatively, use [ListCloudFrontOriginAccessIdentities](https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_ListCloudFrontOriginAccessIdentities.html) in the CloudFront API.

**Example Amazon S3 bucket policy that gives the OAI read access**  
The following example allows the OAI to read objects in the specified bucket (`s3:GetObject`).    
****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Id": "PolicyForCloudFrontPrivateContent",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity <origin access identity ID>"
            },
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::<S3 bucket name>/*"
        }
    ]
}
```

**Example Amazon S3 bucket policy that gives the OAI read and write access**  
The following example allows the OAI to read and write objects in the specified bucket (`s3:GetObject` and `s3:PutObject`). This allows viewers to upload files to your Amazon S3 bucket through CloudFront.    
****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Id": "PolicyForCloudFrontPrivateContent",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity <origin access identity ID>"
            },
            "Action": [
                "s3:GetObject",
                "s3:PutObject"
            ],
            "Resource": "arn:aws:s3:::<S3 bucket name>/*"
        }
    ]
}
```

#### Use Amazon S3 object ACLs (not recommended)
<a name="private-content-updating-s3-acls"></a>

**Important**  
We recommend [using Amazon S3 bucket policies](#private-content-updating-s3-bucket-policies) to give an OAI access to an S3 bucket. You can use access control lists (ACLs) as described in this section, but we don't recommend it.  
Amazon S3 recommends setting [S3 Object Ownership](https://docs.aws.amazon.com/AmazonS3/latest/userguide/about-object-ownership.html) to **bucket owner enforced**, which means that ACLs are disabled for the bucket and the objects in it. When you apply this setting for Object Ownership, you must use bucket policies to give access to the OAI (see the previous section).  
This following section is only for legacy use cases that require ACLs.

You can give a CloudFront OAI access to files in an Amazon S3 bucket by creating or updating the file's ACL in the following ways:
+ Using the Amazon S3 object's **Permissions** tab in the [Amazon S3 console](https://console.aws.amazon.com/s3/home).
+ Using [PutObjectAcl](https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutObjectAcl.html) in the Amazon S3 API.

When you grant access to an OAI using an ACL, you must specify the OAI using its Amazon S3 canonical user ID. In the CloudFront console, you can find this ID under **Security**, **Origin access**, **Identities (legacy)**. If you're using the CloudFront API, use the value of the `S3CanonicalUserId` element that was returned when you created the OAI, or call [ListCloudFrontOriginAccessIdentities](https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_ListCloudFrontOriginAccessIdentities.html) in the CloudFront API.

### Use an origin access identity in Amazon S3 regions that support only signature version 4 authentication
<a name="private-content-origin-access-identity-signature-version-4"></a>

Newer Amazon S3 Regions require that you use Signature Version 4 for authenticated requests. (For the signature versions supported in each Amazon S3 Region, see [Amazon Simple Storage Service endpoints and quotas](https://docs.aws.amazon.com/general/latest/gr/s3.html) in the *AWS General Reference*.) If you're using an origin access identity and if your bucket is in one of the Regions that requires Signature Version 4, note the following:
+ `DELETE`, `GET`, `HEAD`, `OPTIONS`, and `PATCH` requests are supported without qualifications.
+ `POST` requests are not supported.

# Restrict access with VPC origins
<a name="private-content-vpc-origins"></a>

You can use CloudFront to deliver content from applications that are hosted in your virtual private cloud (VPC) private subnets. You can use Application Load Balancers (ALBs), Network Load Balancers (NLBs), and EC2 instances in private subnets as VPC origins.

Here are some reasons why you might want to use VPC origins:
+ **Security** – VPC origins is designed to enhance the security posture of your application by placing your load balancers and EC2 instances in private subnets, making CloudFront the single point of entry. User requests go from CloudFront to the VPC origins over a private, secure connection, providing additional security for your applications.
+ **Management** – VPC origins reduces the operational overhead required for secure connectivity between CloudFront and origins. You can move your origins to private subnets with no public access, and you don’t have to implement access control lists (ACLs) or other mechanisms to restrict access to your origins. This way, you don't have to invest in undifferentiated development work to secure your web applications with CloudFront. 
+ **Scalability and performance** – VPC origins helps you to secure your web applications, freeing up time to focus on growing your critical business applications while improving security and maintaining high performance and global scalability with CloudFront. VPC origins streamlines security management and reduces operational complexity so that you can use CloudFront as the single point of entry for your applications.

**Tip**  
CloudFront supports sharing VPC origins across AWS accounts, whether they're in your organization or not. You can share VPC origins from the CloudFront console or use AWS Resource Access Manager (AWS RAM). For more information, see [Working with shared resources in CloudFront](sharing-resources.md).

## Prerequisites
<a name="vpc-origin-prerequisites"></a>

Before you create a VPC origin for your CloudFront distribution, you must complete the following:

### VPC Configuration
<a name="vpc-configuration"></a>

**Create a virtual private cloud (VPC) on Amazon VPC** in one of the AWS Regions that are supported for VPC origins. For information about creating a VPC, see [Create a VPC plus other VPC resources](https://docs.aws.amazon.com/vpc/latest/userguide/create-vpc.html#create-vpc-and-other-resources) in the *Amazon VPC User Guide*. For a list of supported Regions, see [Supported AWS Regions for VPC origins](#vpc-origins-supported-regions).

Your VPC must include the following:
+ **Internet gateway** – You need to add an internet gateway to the VPC that has your VPC origin resources. The internet gateway is required to denote that the VPC can receive traffic from the internet. The internet gateway is not used for routing traffic to origins inside the subnet, and you don't need to update the routing policies.
+ **Private subnet with at least one available IPv4 address** – CloudFront routes to your subnet by using a service-managed elastic network interface (ENI) that CloudFront creates after you define your VPC origin resource with CloudFront. You must have at least one available IPv4 address in your private subnet so that the ENI creation process can succeed. The IPv4 address can be private, and there is no additional cost for it. IPv6-only subnets are not supported.

### Origin Resources
<a name="origin-resources"></a>

In the private subnet, launch an Application Load Balancer, a Network Load Balancer, or an EC2 instance to use as your origin. The resource you launch must be fully deployed and in Active status before you can use it for a VPC origin.

**Origin restrictions:**
+ Gateway Load Balancers cannot be added as origins
+ Dual-stack Network Load Balancers cannot be added as origins
+ Network Load Balancers with TLS listeners cannot be added as origins
+ To be used as a VPC origin, a Network Load Balancer must have a security group attached to it

### Security Group Configuration
<a name="security-group-configuration"></a>

Your VPC origin resources (Application Load Balancer, Network Load Balancer, or EC2 instance) must have a security group attached. When you create a VPC origin, CloudFront automatically creates a service-managed security group with the naming pattern `CloudFront-VPCOrigins-Service-SG`. This security group is fully managed by AWS, and should not be edited.

To allow traffic from CloudFront to reach your VPC origin, update the security group attached to your origin resource (ALB, NLB, or EC2 instance) to allow inbound traffic using one of the following methods:
+ **Option 1:** Allow traffic from the CloudFront managed prefix list. For more information, see [Use the CloudFront managed prefix list](LocationsOfEdgeServers.md#managed-prefix-list). This can be done before VPC origin created as well.
+ **Option 2:** Allow traffic from the CloudFront service-managed security group (`CloudFront-VPCOrigins-Service-SG`). This can be done only after the VPC origin is created and the service-managed security group is created. This configuration is further restrictive as it restricts the traffic only to your CloudFront distributions.

**Important**  
Do not create your own security group with a name starting with `CloudFront-VPCOrigins-Service-SG`. This is an AWS reserved naming pattern for service-managed security groups. For more information, see [Creating a security group](https://docs.aws.amazon.com/vpc/latest/userguide/creating-security-groups.html).

### Protocol and Feature Restrictions
<a name="protocol-feature-restrictions"></a>

VPC origins do not support the following:
+ WebSockets
+ gRPC traffic
+ Origin request and origin response triggers with Lambda@Edge

## Create a VPC origin (new distribution)
<a name="new-vpc-origin"></a>

The following procedure shows you how to create a VPC origin for your new CloudFront distribution in the CloudFront console. Alternatively, you can use the [CreateVpcOrigin](https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_CreateVpcOrigin.html) and [CreateDistribution](https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_CreateDistribution.html) API operations with the AWS CLI or an AWS SDK.

**To create a VPC origin for a new CloudFront distribution**

1. Open the CloudFront console at [https://console.aws.amazon.com/cloudfront/v4/home](https://console.aws.amazon.com/cloudfront/v4/home).

1. Choose **VPC origins**, **Create VPC origin**.

1. Fill out the required fields. For **Origin ARN**, select the ARN of your Application Load Balancer, Network Load Balancer, or EC2 instance. If you don’t see the ARN, you can copy your specific resource ARN and paste it here instead.

1. Choose **Create VPC origin**.

1. Wait for your VPC origin status to change to **Deployed**. This can take up to 15 minutes.

1. Choose **Distributions**, **Create distribution**.

1. For **Origin domain**, select your VPC origins resource from the dropdown list.

   If your VPC origin is an EC2 instance, copy and paste the **Private IP DNS name** of the instance into the **Origin domain** field.

1. Finish creating your distribution. For more information, see [Create a CloudFront distribution in the console](distribution-web-creating-console.md#create-console-distribution).

## Create a VPC origin (existing distribution)
<a name="existing-vpc-origin"></a>

The following procedure shows you how to create a VPC origin for your existing CloudFront distribution in the CloudFront console, which helps to ensure continuous availability of your applications. Alternatively, you can use the [CreateVpcOrigin](https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_CreateVpcOrigin.html) and [UpdateDistributionWithStagingConfig](https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_UpdateDistributionWithStagingConfig.html) API operations with the AWS CLI or an AWS SDK.

Optionally, you could choose to add your VPC origin to your existing distribution without creating a staging distribution.

**To create a VPC origin for your existing CloudFront distribution**

1. Open the CloudFront console at [https://console.aws.amazon.com/cloudfront/v4/home](https://console.aws.amazon.com/cloudfront/v4/home).

1. Choose **VPC origins**, **Create VPC origin**.

1. Fill out the required fields. For **Origin ARN**, select the ARN of your Application Load Balancer, Network Load Balancer, or EC2 instance. If you don’t see the ARN, you can copy your specific resource ARN and paste it here instead.

1. Choose **Create VPC origin**.

1. Wait for your VPC origin status to change to **Deployed**. This can take up to 15 minutes.

1. In the navigation pane, choose **Distributions**.

1. Choose the ID of your distribution.

1. On the **General** tab, under **Continuous deployment**, choose **Create staging distribution**. For more information, see [Use CloudFront continuous deployment to safely test CDN configuration changes](continuous-deployment.md).

1. Follow the steps in the **Create staging distribution** wizard to create a staging distribution. Include the following steps:
   + For **Origins**, choose **Create origin**.
   + For **Origin domain**, select your VPC origins resource from the dropdown menu.

     If your VPC origin is an EC2 instance, copy and paste the **Private IP DNS name** of the instance into the **Origin domain** field.
   + Choose **Create origin**.

1. In your staging distribution, test the VPC origin.

1. Promote the staging distribution configuration to your primary distribution. For more information, see [Promote a staging distribution configuration](working-with-staging-distribution-continuous-deployment-policy.md#promote-staging-distribution-configuration).

1. Remove public access to your VPC origin by making the subnet private. After you do this, the VPC origin won't be discoverable over the internet, but CloudFront will still have private access to it. For more information, see [Associate or disassociate a subnet with a route table](https://docs.aws.amazon.com/vpc/latest/userguide/WorkWithRouteTables.html#AssociateSubnet) in the *Amazon VPC User Guide*.

## Update a VPC origin
<a name="update-vpc-origin"></a>

The following procedure shows you how to update a VPC origin for your CloudFront distribution in the CloudFront console. Alternatively, you can use the [UpdateDistribution](https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_UpdateDistribution.html) and [UpdateVpcOrigin](https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_UpdateVpcOrigin.html) API operations with the AWS CLI or an AWS SDK.

**To update an existing VPC origin for your CloudFront distribution**

1. Open the CloudFront console at [https://console.aws.amazon.com/cloudfront/v4/home](https://console.aws.amazon.com/cloudfront/v4/home).

1. In the navigation pane, choose **Distributions**.

1. Choose the ID of your distribution.

1. Choose the **Behaviors** tab.

1. Make sure that the VPC origin is not the default origin for your cache behavior. 

1. Choose the **Origins** tab.

1. Select the VPC origin that you're going to update and choose **Delete**. This disassociates the VPC origin from your distribution. Repeat steps 2-7 to disassociate the VPC origin from any other distributions.

1. Choose **VPC origins**.

1. Select the VPC origin and choose **Edit**.

1. Make your updates and choose **Update VPC origin**.

1. Wait for your VPC origin status to change to **Deployed**. This can take up to 15 minutes.

1. In the navigation pane, choose **Distributions**.

1. Choose the ID of your distribution.

1. Choose the **Origins** tab.

1. Choose **Create origin**.

1. For **Origin domain**, select your VPC origins resource from the dropdown menu.

   If your VPC origin is an EC2 instance, copy and paste the **Private IP DNS name** of the instance into the **Origin domain** field.

1. Choose **Create origin**. This associates the VPC origin with your distribution again. Repeat steps 12-17 to associate the updated VPC origin with any other distributions.

## Supported AWS Regions for VPC origins
<a name="vpc-origins-supported-regions"></a>

VPC origins are currently supported in the following commercial AWS Regions. Availability Zone (AZ) exceptions are noted.

[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-vpc-origins.html)

# Restrict access to an Amazon S3 Multi-Region Access Point origin
<a name="private-content-restricting-access-to-s3-mrap"></a>

You can use origin access control (OAC) to restrict access to an Amazon S3 Multi-Region Access Point origin. S3 Multi-Region Access Points provide a global endpoint that routes requests to the closest S3 bucket based on network latency.

For information about using OAC with a standard Amazon S3 bucket origin, see [Restrict access to an Amazon S3 origin](private-content-restricting-access-to-s3.md).

## Prerequisites
<a name="oac-prerequisites-s3-mrap"></a>

Before you create and set up OAC, you must have a CloudFront distribution with an Amazon S3 Multi-Region Access Point origin. The origin domain name must use the S3 Multi-Region Access Point hostname format:

`multi-region-access-point-alias.accesspoint.s3-global.amazonaws.com`

For more information about creating an S3 Multi-Region Access Point, see [Creating Multi-Region Access Points](https://docs.aws.amazon.com/AmazonS3/latest/userguide/CreatingMultiRegionAccessPoints.html) in the *Amazon Simple Storage Service User Guide*.

## Grant CloudFront permission to access the S3 Multi-Region Access Point
<a name="oac-permission-to-access-s3-mrap"></a>

Update the Multi-Region Access Point policy to allow the CloudFront service principal (`cloudfront.amazonaws.com`) to access the Multi-Region Access Point. Use a `Condition` element in the policy to allow CloudFront to access the Multi-Region Access Point only when the request is on behalf of the CloudFront distribution that contains the origin.

For information about adding or modifying a Multi-Region Access Point policy, see [Multi-Region Access Point policy examples](https://docs.aws.amazon.com/AmazonS3/latest/userguide/MultiRegionAccessPointPermissions.html) in the *Amazon Simple Storage Service User Guide*.

**Example Multi-Region Access Point policy for CloudFront OAC**  

```
{
    "Version": "2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "AllowCloudFrontOACAccess",
            "Effect": "Allow",
            "Principal": {
                "Service": "cloudfront.amazonaws.com"
            },
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3::111122223333:accesspoint/Multi-Region-Access-Point-Alias.mrap/object/*",
            "Condition": {
                "StringEquals": {
                    "aws:SourceArn": "arn:aws:cloudfront::111122223333:distribution/CloudFront distribution ID"
                }
            }
        }
    ]
}
```

## Grant CloudFront permission to access the underlying S3 buckets
<a name="oac-permission-to-access-s3-mrap-buckets"></a>

In addition to the Multi-Region Access Point policy, you must also grant CloudFront permission to access each of the underlying S3 buckets that are associated with the Multi-Region Access Point. You can do this in one of two ways:

### Option 1: Grant access only to CloudFront
<a name="oac-s3-mrap-bucket-option1"></a>

Add a bucket policy to each S3 bucket that allows the CloudFront service principal to access the bucket. Use this option when you also need to allow direct access to the bucket from other sources.

**Example S3 bucket policy for an underlying bucket**  

```
{
    "Version": "2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "AllowCloudFrontOACAccessViaMRAP",
            "Effect": "Allow",
            "Principal": {
                "Service": "cloudfront.amazonaws.com"
            },
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::amzn-s3-demo-bucket-us-east-1/*",
            "Condition": {
                "StringEquals": {
                    "aws:SourceArn": "arn:aws:cloudfront::111122223333:distribution/CloudFront distribution ID"
                }
            }
        }
    ]
}
```

### Option 2: Delegate full bucket access to the Multi-Region Access Point
<a name="oac-s3-mrap-bucket-option2"></a>

Grant the Multi-Region Access Point full access to each underlying bucket. With this approach, all access to the bucket is controlled by the Multi-Region Access Point policy, which simplifies access management. We recommend this option for use cases that don't require direct access to the bucket.

**Example S3 bucket policy that delegates access to the Multi-Region Access Point**  

```
{
    "Version": "2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "DelegateAccessToMRAP",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:*",
            "Resource": [
                "arn:aws:s3:::amzn-s3-demo-bucket-us-east-1",
                "arn:aws:s3:::amzn-s3-demo-bucket-us-east-1/*"
            ],
            "Condition": {
                "StringEquals": {
                    "s3:DataAccessPointArn": "arn:aws:s3::111122223333:accesspoint/Multi-Region-Access-Point-Alias.mrap"
                }
            }
        }
    ]
}
```

For more information, see [Multi-Region Access Point policy example](https://docs.aws.amazon.com/AmazonS3/latest/userguide/MultiRegionAccessPointPermissions.html#MultiRegionAccessPointPolicyExamples) in the *Amazon Simple Storage Service User Guide*.

**Important**  
You must add this bucket policy to every S3 bucket that is associated with the Multi-Region Access Point. If any bucket is missing the policy, CloudFront requests routed to that bucket will be denied.

### SSE-KMS
<a name="oac-s3-mrap-sse-kms"></a>

If the objects in the underlying S3 buckets are encrypted using server-side encryption with AWS KMS (SSE-KMS), you must make sure that the CloudFront distribution has permission to use the AWS KMS key. Because S3 Multi-Region Access Points can route requests to buckets in multiple Regions, you must add a statement to the KMS key policy in each Region where an underlying bucket uses SSE-KMS. For information about how to modify a key policy, see [Changing a key policy](https://docs.aws.amazon.com/kms/latest/developerguide/key-policy-modifying.html) in the *AWS Key Management Service Developer Guide*.

**Example KMS key policy statement**  
The following example shows a KMS key policy statement that allows the CloudFront distribution with OAC to access a KMS key for SSE-KMS.  

```
{
    "Sid": "AllowCloudFrontServicePrincipalSSE-KMS",
    "Effect": "Allow",
    "Principal": {
        "Service": "cloudfront.amazonaws.com"
    },
    "Action": [
        "kms:Decrypt",
        "kms:Encrypt",
        "kms:GenerateDataKey*"
    ],
    "Resource": "*",
    "Condition": {
        "StringEquals": {
            "aws:SourceArn": "arn:aws:cloudfront::111122223333:distribution/CloudFront distribution ID"
        }
    }
}
```

**Important**  
You must add this key policy statement to the KMS key in every Region where an underlying S3 bucket uses SSE-KMS encryption.

## Create the origin access control
<a name="create-oac-s3-mrap"></a>

To create an origin access control (OAC), you can use the AWS Management Console, CloudFormation, the AWS CLI, or the CloudFront API.

------
#### [ Console ]

**To create an origin access control**

1. Sign in to the AWS Management Console and open the CloudFront console at [https://console.aws.amazon.com/cloudfront/v4/home](https://console.aws.amazon.com/cloudfront/v4/home).

1. In the navigation pane, choose **Origin access**.

1. Choose **Create control setting**.

1. On the **Create control setting** form, do the following:

   1. In the **Details** pane, enter a **Name** and (optionally) a **Description** for the origin access control.

   1. In the **Settings** pane, we recommend that you leave the default setting (**Sign requests (recommended)**). For more information, see [Advanced settings for origin access control](private-content-restricting-access-to-s3.md#oac-advanced-settings-s3).

1. Choose **S3 Multi-Region Access Point** from the **Origin type** dropdown.

1. Choose **Create**.

   After the OAC is created, make note of the **Name**. You need this in the following procedure.

**To add an origin access control to an S3 Multi-Region Access Point origin in a distribution**

1. Open the CloudFront console at [https://console.aws.amazon.com/cloudfront/v4/home](https://console.aws.amazon.com/cloudfront/v4/home).

1. Choose a distribution with an S3 Multi-Region Access Point origin that you want to add the OAC to, then choose the **Origins** tab.

1. Select the S3 Multi-Region Access Point origin that you want to add the OAC to, then choose **Edit**.

1. For **Origin access**, choose **Origin access control settings (recommended)**.

1. From the **Origin access control** dropdown menu, choose the OAC that you want to use.

1. Choose **Save changes**.

The distribution starts deploying to all of the CloudFront edge locations. When an edge location receives the new configuration, it signs all requests that it sends to the S3 Multi-Region Access Point origin.

------
#### [ CLI ]

Use the **create-origin-access-control** command:

```
aws cloudfront create-origin-access-control \
    --origin-access-control-config '{
        "Name": "my-s3-mrap-oac",
        "Description": "OAC for S3 Multi-Region Access Point",
        "SigningProtocol": "sigv4a",
        "SigningBehavior": "always",
        "OriginAccessControlOriginType": "s3mrap"
    }'
```

------
#### [ CloudFormation ]

Specify the following values in the `OriginAccessControlConfig`:
+ `SigningProtocol`: `sigv4a`
+ `SigningBehavior`: `always`, `never`, or `no-override`
+ `OriginAccessControlOriginType`: `s3mrap`

**Example CloudFormation template**  

```
Type: AWS::CloudFront::OriginAccessControl
Properties:
  OriginAccessControlConfig:
    Description: An optional description for the origin access control
    Name: my-s3-mrap-oac
    OriginAccessControlOriginType: s3mrap
    SigningBehavior: always
    SigningProtocol: sigv4a
```

------

## Signing behavior
<a name="oac-signing-behavior-s3-mrap"></a>

The signing behavior options for S3 Multi-Region Access Point origins are the same as those for regular Amazon S3 bucket origins. For more information, see [Advanced settings for origin access control](private-content-restricting-access-to-s3.md#oac-advanced-settings-s3) in *Restrict access to an Amazon S3 origin*.