

# 将 CloudFront Functions 与源双向 TLS 结合使用
<a name="origin-mtls-cloudfront-functions"></a>

CloudFront Functions 在边缘提供轻量级的无服务器计算，用于自定义内容交付。在 CloudFront Functions 中使用源双向 TLS 时，需要注意有关源选择和操作的特定行为和限制。

## 支持的 CloudFront Functions 操作
<a name="supported-cloudfront-functions-operations"></a>

CloudFront Functions 可以通过以下方式与启用了 mTLS 的源进行交互：

### updateRequestOrigin()
<a name="update-request-origin-function"></a>

updateRequestOrigin() 函数在使用启用了 mTLS 的源时支持进行有限的修改：
+ **在源 mTLS 源之间切换：**您可以更新请求以路由到使用源 mTLS 的不同源，前提是这两个源都使用**相同的客户端证书**。这支持您在保持双向 TLS 身份验证的同时实现自定义路由逻辑。通过 `selectRequestOriginById()` 和 `createRequestOriginGroup()` API 支持在使用不同证书的源之间进行切换。
+ **禁用源 mTLS：**您可以通过在函数中设置 `mTLSConfig: 'off'`，从启用了 mTLS 的源切换到非 mTLS 源。这为根据请求特征有条件地禁用双向 TLS 身份验证提供了灵活性。

#### 示例：在具有相同证书的源 mTLS 源之间切换
<a name="example-switching-mtls-origins"></a>

```
import cf from 'cloudfront';

function handler(event) {
    var request = event.request;

    // Route to different origin based on request path
    if (request.uri.startsWith('/api/v2')) {
        cf.updateRequestOrigin({
            "domainName": "api-v2.example.com",
            "mTLSConfig": "inherit",
            // If no value is provided for mTLSConfig, it defaults to inherit
            // Both origins must use the same certificate
        });
    }

    return request;
}
```

#### 示例：有条件地禁用源 mTLS
<a name="example-disabling-mtls"></a>

```
import cf from 'cloudfront';

function handler(event) {
    var request = event.request;

    // Disable mTLS for specific paths
    if (request.uri.startsWith('/public')) {
        cf.updateRequestOrigin({
            "domainName": "public-origin.example.com",
            "mTLSConfig": "off"
        });
    }

    return request;
}
```

### selectRequestOriginById()
<a name="select-request-origin-by-id-mtls"></a>

`selectRequestOriginById()` 函数支持选择启用了双向 TLS（源）的源。您可以使用此函数将请求动态路由到在分配中配置的启用了 mTLS 的源。在按 ID 选择启用了双向 TLS（源）的源时，CloudFront 使用在分配设置中为该源配置的客户端证书。

#### 示例：按 ID 选择启用了双向 TLS（源）的源
<a name="example-select-mtls-origin-by-id"></a>

```
import cf from 'cloudfront';

function handler(event) {
    var request = event.request;

    // Select mTLS-enabled origin based on request characteristics
    if (request.uri.startsWith('/secure-api')) {
        cf.selectRequestOriginById("mtls-origin-1");
    }

    return request;
}
```

### createRequestOriginGroup()
<a name="create-request-origin-group-mtls"></a>

`createRequestOriginGroup()` 函数支持创建包含启用了双向 TLS（源）的源的源组。您可以在 CloudFront Functions 中为失效转移场景动态创建具有启用了 mTLS 的源的源组。

#### 示例：创建具有启用了双向 TLS（源）的源的源组
<a name="example-create-mtls-origin-group"></a>

```
import cf from 'cloudfront';

function handler(event) {
    // Create origin group with mTLS-enabled primary and failover origins
    cf.createRequestOriginGroup({
        "originIds": ["mtls-origin-primary", "mtls-origin-failover"],
        "failoverCriteria": {
            "statusCodes": [500, 502, 503, 504]
        }
    });

    return event.request;
}
```