deploying-custom-domain-rest-api

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Custom Domain REST API with Lambda and Request Authorizer

带Lambda和请求授权器的自定义域名REST API

Overview

概述

This SOP deploys a REST API with a Regional custom domain name, a Lambda backend function, and a request-based Lambda authorizer. It handles ACM certificate provisioning, IAM role creation, Lambda function deployment, API Gateway REST API creation with a custom authorizer, custom domain configuration, base path mapping, and Route 53 DNS setup.
The architecture includes:
  • An API Gateway REST API with an endpoint type of REGIONAL
  • A request-based Lambda authorizer that validates headers, query string parameters, and stage variables
  • A Lambda backend function at
    GET /example
  • A custom domain name with TLS 1.2
  • A base path mapping connecting the custom domain to the API stage
  • A Route 53 A-alias record pointing the custom domain to the API Gateway Regional endpoint
Important: This SOP uses Regional endpoints. If the user requests a private endpoint, inform them that this skill covers Regional endpoints only. Private endpoints require VPC endpoint configuration.
本标准操作流程(SOP)用于部署带有区域自定义域名、Lambda后端函数和基于请求的Lambda授权器的REST API。它处理ACM证书配置、IAM角色创建、Lambda函数部署、带自定义授权器的API Gateway REST API创建、自定义域名配置、基础路径映射以及Route 53 DNS设置。
架构包含:
  • 端点类型为REGIONAL的API Gateway REST API
  • 验证请求头、查询字符串参数和阶段变量的基于请求的Lambda授权器
  • 位于
    GET /example
    的Lambda后端函数
  • 支持TLS 1.2的自定义域名
  • 将自定义域名连接到API阶段的基础路径映射
  • 将自定义域名指向API Gateway区域端点的Route 53 A别名记录
重要提示:本SOP使用区域端点。如果用户请求私有端点,请告知用户本技能仅涵盖区域端点。私有端点需要VPC端点配置。

Parameters

参数

  • custom_domain_name (required): Fully qualified domain name for the API (e.g.,
    api.example.com
    )
  • region (required): AWS Region for all resources. The ACM certificate must be in this same Region for Regional endpoints
  • hosted_zone_id (required): Route 53 hosted zone ID for the domain
  • acm_certificate_arn (optional): ARN of an existing ACM certificate covering the custom domain. If not provided, Step 2 creates one
  • stage_name (optional, default: "dev"): API Gateway stage name
Constraints for parameter acquisition:
  • You MUST ask for all required parameters upfront in a single prompt rather than one at a time
  • You MUST support multiple input methods (direct input, file path, URL)
  • You MUST confirm successful acquisition of all parameters before proceeding
  • You MUST inform the user that this skill uses hardcoded demo authorization values (headerValue1, queryValue1, stageValue1) that are NOT suitable for production. For production, use AWS Secrets Manager or Systems Manager Parameter Store to manage authorization credentials. See: https://docs.aws.amazon.com/secretsmanager/latest/userguide/intro.html
  • You MUST validate that custom_domain_name is a valid FQDN
  • custom_domain_name(必填):API的完全限定域名(例如:
    api.example.com
  • region(必填):所有资源所在的AWS区域。对于区域端点,ACM证书必须位于同一区域
  • hosted_zone_id(必填):域名对应的Route 53托管区域ID
  • acm_certificate_arn(可选):覆盖自定义域名的现有ACM证书ARN。如果未提供,步骤2将创建一个新证书
  • stage_name(可选,默认值:"dev"):API Gateway阶段名称
参数获取约束:
  • 必须在单个提示中一次性请求所有必填参数,而非逐个询问
  • 必须支持多种输入方式(直接输入、文件路径、URL)
  • 必须在继续操作前确认已成功获取所有参数
  • 必须告知用户本技能使用硬编码的演示授权值(headerValue1、queryValue1、stageValue1),这些值不适合生产环境。生产环境中,请使用AWS Secrets Manager或Systems Manager Parameter Store管理授权凭据。参考:https://docs.aws.amazon.com/secretsmanager/latest/userguide/intro.html
  • 必须验证custom_domain_name是有效的完全限定域名

Steps

步骤

0. Verify Dependencies

0. 验证依赖项

Constraints:
  • You MUST verify the following tools are available: aws-cli, python3, sed, node (v22+)
  • You MUST inform the user about any missing tools with a clear message
  • You MUST ask if the user wants to proceed despite missing tools
  • You MUST respect the customer's decision to abort at any point
  • You MUST explain to the customer what step is being executed, why, and which tool is being called
约束:
  • 必须验证以下工具是否可用:aws-cli、python3、sed、node(v22+)
  • 必须向用户清晰告知任何缺失的工具
  • 必须询问用户是否要在工具缺失的情况下继续操作
  • 必须尊重用户随时中止操作的决定
  • 必须向用户解释当前正在执行的步骤、原因以及调用的工具

1. Retrieve AWS Account ID

1. 获取AWS账户ID

This step MUST be performed before all other steps.
Constraints:
  • You MUST retrieve the account ID with:
    aws sts get-caller-identity --query 'Account' --output text
  • You MUST store the result as {account_id} and reuse it in all subsequent steps that reference {account_id}
  • You MUST abort if credentials are not configured
此步骤必须在所有其他步骤之前执行。
约束:
  • 必须通过以下命令获取账户ID:
    aws sts get-caller-identity --query 'Account' --output text
  • 必须将结果存储为{account_id},并在所有后续引用{account_id}的步骤中重复使用
  • 如果未配置凭据,必须中止操作

2. Request ACM Certificate

2. 请求ACM证书

Skip this step if acm_certificate_arn is already provided.
Constraints:
  • You MUST request the certificate with:
    aws acm request-certificate --domain-name {custom_domain_name} --validation-method DNS --region {region}
  • You MUST capture the CertificateArn from the response
  • You MUST retrieve the DNS validation record with:
    aws acm describe-certificate --certificate-arn {cert_arn} --query 'Certificate.DomainValidationOptions[0].ResourceRecord' --region {region}
  • You MUST create the validation CNAME in Route 53 with:
    aws route53 change-resource-record-sets --hosted-zone-id {hosted_zone_id} --change-batch '{"Changes":[{"Action":"UPSERT","ResourceRecordSet":{"Name":"{validation_name}","Type":"CNAME","TTL":300,"ResourceRecords":[{"Value":"{validation_value}"}]}}]}'
  • You MUST wait for certificate validation with:
    aws acm wait certificate-validated --certificate-arn {cert_arn} --region {region}
  • The wait command may take up to 30 minutes. If it times out, check status manually with:
    aws acm describe-certificate --certificate-arn {cert_arn} --query 'Certificate.Status' --region {region}
    and retry the wait if status is still PENDING_VALIDATION
  • You MUST NOT proceed until the certificate status is ISSUED
  • You MUST store the certificate ARN as acm_certificate_arn for use in Step 7
如果已提供acm_certificate_arn,则跳过此步骤。
约束:
  • 必须通过以下命令请求证书:
    aws acm request-certificate --domain-name {custom_domain_name} --validation-method DNS --region {region}
  • 必须从响应中捕获CertificateArn
  • 必须通过以下命令获取DNS验证记录:
    aws acm describe-certificate --certificate-arn {cert_arn} --query 'Certificate.DomainValidationOptions[0].ResourceRecord' --region {region}
  • 必须通过以下命令在Route 53中创建验证CNAME:
    aws route53 change-resource-record-sets --hosted-zone-id {hosted_zone_id} --change-batch '{"Changes":[{"Action":"UPSERT","ResourceRecordSet":{"Name":"{validation_name}","Type":"CNAME","TTL":300,"ResourceRecords":[{"Value":"{validation_value}"}]}}]}'
  • 必须通过以下命令等待证书验证完成:
    aws acm wait certificate-validated --certificate-arn {cert_arn} --region {region}
  • 等待命令可能需要长达30分钟。如果超时,请通过以下命令手动检查状态:
    aws acm describe-certificate --certificate-arn {cert_arn} --query 'Certificate.Status' --region {region}
    ,如果状态仍为PENDING_VALIDATION,则重试等待命令
  • 必须在证书状态变为ISSUED后才能继续操作
  • 必须将证书ARN存储为acm_certificate_arn,以便在步骤7中使用

3. Create IAM Execution Roles

3. 创建IAM执行角色

Constraints:
  • You MUST create two IAM roles: one for the authorizer Lambda and one for the example function Lambda
  • Both roles use the same trust policy from
    scripts/lambda-trust-policy.json
    . The trust policy includes an
    aws:SourceAccount
    condition scoped to the user's account ID
  • You MUST create a working copy of the trust policy and replace the
    ACCOUNT_ID
    placeholder with the actual account ID from Step 1. Use:
    sed 's/ACCOUNT_ID/{account_id}/' scripts/lambda-trust-policy.json > /tmp/lambda-trust-policy.json
  • You MUST create the authorizer role with:
    aws iam create-role --role-name request-authorizer-role --assume-role-policy-document file:///tmp/lambda-trust-policy.json
  • You MUST attach the basic execution policy to the authorizer role with:
    aws iam attach-role-policy --role-name request-authorizer-role --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
  • You MUST create the example function role with:
    aws iam create-role --role-name example-function-role --assume-role-policy-document file:///tmp/lambda-trust-policy.json
  • You MUST attach the basic execution policy to the example function role with:
    aws iam attach-role-policy --role-name example-function-role --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
  • You MUST capture the role ARNs from each create-role response for use in Step 4
  • You MUST wait at least 10 seconds after role creation before creating Lambda functions because IAM role propagation is eventually consistent
约束:
  • 必须创建两个IAM角色:一个用于授权器Lambda,一个用于示例函数Lambda
  • 两个角色均使用
    scripts/lambda-trust-policy.json
    中的相同信任策略。该信任策略包含一个限定于用户账户ID的
    aws:SourceAccount
    条件
  • 必须创建信任策略的工作副本,并将
    ACCOUNT_ID
    占位符替换为步骤1中获取的实际账户ID。使用命令:
    sed 's/ACCOUNT_ID/{account_id}/' scripts/lambda-trust-policy.json > /tmp/lambda-trust-policy.json
  • 必须通过以下命令创建授权器角色:
    aws iam create-role --role-name request-authorizer-role --assume-role-policy-document file:///tmp/lambda-trust-policy.json
  • 必须通过以下命令将基础执行策略附加到授权器角色:
    aws iam attach-role-policy --role-name request-authorizer-role --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
  • 必须通过以下命令创建示例函数角色:
    aws iam create-role --role-name example-function-role --assume-role-policy-document file:///tmp/lambda-trust-policy.json
  • 必须通过以下命令将基础执行策略附加到示例函数角色:
    aws iam attach-role-policy --role-name example-function-role --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
  • 必须从每个create-role响应中捕获角色ARN,以便在步骤4中使用
  • 必须在角色创建后等待至少10秒再创建Lambda函数,因为IAM角色的传播最终是一致的

4. Create and Deploy Lambda Functions

4. 创建并部署Lambda函数

Constraints:
  • You MUST create two Lambda functions: the request authorizer and the example function
  • For the authorizer function:
    • You MUST create the function with inline code. First write the code to a file and package it:
      python3 -c "import zipfile,io,base64; z=io.BytesIO(); f=zipfile.ZipFile(z,'w'); f.writestr('index.mjs', open('scripts/authorizer.mjs').read()); f.close(); open('/tmp/authorizer.zip','wb').write(z.getvalue())"
    • Then create the function with:
      aws lambda create-function --function-name request-authorizer --runtime nodejs22.x --handler index.handler --role {authorizer_role_arn} --zip-file fileb:///tmp/authorizer.zip --timeout 10 --region {region}
  • For the example function:
    • You MUST create the function with inline code. First write the code to a file and package it:
      python3 -c "import zipfile,io; z=io.BytesIO(); f=zipfile.ZipFile(z,'w'); f.writestr('index.mjs', open('scripts/example_function.mjs').read()); f.close(); open('/tmp/example_function.zip','wb').write(z.getvalue())"
    • Then create the function with:
      aws lambda create-function --function-name example-function --runtime nodejs22.x --handler index.handler --role {example_role_arn} --zip-file fileb:///tmp/example_function.zip --timeout 10 --region {region}
  • You MUST verify each function was created by calling:
    aws lambda get-function --function-name {function_name} --region {region}
约束:
  • 必须创建两个Lambda函数:请求授权器和示例函数
  • 对于授权器函数:
    • 必须使用内联代码创建函数。首先将代码写入文件并打包:
      python3 -c "import zipfile,io,base64; z=io.BytesIO(); f=zipfile.ZipFile(z,'w'); f.writestr('index.mjs', open('scripts/authorizer.mjs').read()); f.close(); open('/tmp/authorizer.zip','wb').write(z.getvalue())"
    • 然后通过以下命令创建函数:
      aws lambda create-function --function-name request-authorizer --runtime nodejs22.x --handler index.handler --role {authorizer_role_arn} --zip-file fileb:///tmp/authorizer.zip --timeout 10 --region {region}
  • 对于示例函数:
    • 必须使用内联代码创建函数。首先将代码写入文件并打包:
      python3 -c "import zipfile,io; z=io.BytesIO(); f=zipfile.ZipFile(z,'w'); f.writestr('index.mjs', open('scripts/example_function.mjs').read()); f.close(); open('/tmp/example_function.zip','wb').write(z.getvalue())"
    • 然后通过以下命令创建函数:
      aws lambda create-function --function-name example-function --runtime nodejs22.x --handler index.handler --role {example_role_arn} --zip-file fileb:///tmp/example_function.zip --timeout 10 --region {region}
  • 必须通过以下命令验证每个函数是否创建成功:
    aws lambda get-function --function-name {function_name} --region {region}

5. Create REST API with Request Authorizer

5. 创建带请求授权器的REST API

Constraints:
  • You MUST create the REST API with:
    aws apigateway create-rest-api --name custom-domain-api --endpoint-configuration types=REGIONAL --region {region}
  • You MUST capture the API id and get the root resource ID with:
    aws apigateway get-resources --rest-api-id {api_id} --region {region}
  • You MUST create the request-based Lambda authorizer with:
    aws apigateway create-authorizer --rest-api-id {api_id} --name request-authorizer --type REQUEST --authorizer-uri 'arn:aws:apigateway:{region}:lambda:path/2015-03-31/functions/arn:aws:lambda:{region}:{account_id}:function:request-authorizer/invocations' --identity-source 'method.request.header.HeaderAuth1,method.request.querystring.QueryString1,context.stage' --region {region}
  • You MUST capture the authorizer ID from the response
  • You MUST grant API Gateway permission to invoke the authorizer with:
    aws lambda add-permission --function-name request-authorizer --statement-id apigateway-auth-invoke --action lambda:InvokeFunction --principal apigateway.amazonaws.com --source-arn 'arn:aws:execute-api:{region}:{account_id}:{api_id}/authorizers/{authorizer_id}' --region {region}
  • You MUST create the /example resource with:
    aws apigateway create-resource --rest-api-id {api_id} --parent-id {root_resource_id} --path-part example --region {region}
  • You MUST create the GET method with:
    aws apigateway put-method --rest-api-id {api_id} --resource-id {example_resource_id} --http-method GET --authorization-type CUSTOM --authorizer-id {authorizer_id} --region {region}
  • You MUST create the Lambda proxy integration with:
    aws apigateway put-integration --rest-api-id {api_id} --resource-id {example_resource_id} --http-method GET --type AWS_PROXY --integration-http-method POST --uri 'arn:aws:apigateway:{region}:lambda:path/2015-03-31/functions/arn:aws:lambda:{region}:{account_id}:function:example-function/invocations' --region {region}
  • You MUST grant API Gateway permission to invoke the example function with:
    aws lambda add-permission --function-name example-function --statement-id apigateway-invoke --action lambda:InvokeFunction --principal apigateway.amazonaws.com --source-arn 'arn:aws:execute-api:{region}:{account_id}:{api_id}/*/GET/example' --region {region}
  • You MUST NOT create the deployment until all resources, methods, and integrations are configured
  • You MUST configure request validation to reject malformed query parameters and headers by validating that QueryString1 and HeaderAuth1 match expected patterns and enforcing size limits
约束:
  • 必须通过以下命令创建REST API:
    aws apigateway create-rest-api --name custom-domain-api --endpoint-configuration types=REGIONAL --region {region}
  • 必须捕获API ID并通过以下命令获取根资源ID:
    aws apigateway get-resources --rest-api-id {api_id} --region {region}
  • 必须通过以下命令创建基于请求的Lambda授权器:
    aws apigateway create-authorizer --rest-api-id {api_id} --name request-authorizer --type REQUEST --authorizer-uri 'arn:aws:apigateway:{region}:lambda:path/2015-03-31/functions/arn:aws:lambda:{region}:{account_id}:function:request-authorizer/invocations' --identity-source 'method.request.header.HeaderAuth1,method.request.querystring.QueryString1,context.stage' --region {region}
  • 必须从响应中捕获授权器ID
  • 必须通过以下命令授予API Gateway调用授权器的权限:
    aws lambda add-permission --function-name request-authorizer --statement-id apigateway-auth-invoke --action lambda:InvokeFunction --principal apigateway.amazonaws.com --source-arn 'arn:aws:execute-api:{region}:{account_id}:{api_id}/authorizers/{authorizer_id}' --region {region}
  • 必须通过以下命令创建/example资源:
    aws apigateway create-resource --rest-api-id {api_id} --parent-id {root_resource_id} --path-part example --region {region}
  • 必须通过以下命令创建GET方法:
    aws apigateway put-method --rest-api-id {api_id} --resource-id {example_resource_id} --http-method GET --authorization-type CUSTOM --authorizer-id {authorizer_id} --region {region}
  • 必须通过以下命令创建Lambda代理集成:
    aws apigateway put-integration --rest-api-id {api_id} --resource-id {example_resource_id} --http-method GET --type AWS_PROXY --integration-http-method POST --uri 'arn:aws:apigateway:{region}:lambda:path/2015-03-31/functions/arn:aws:lambda:{region}:{account_id}:function:example-function/invocations' --region {region}
  • 必须通过以下命令授予API Gateway调用示例函数的权限:
    aws lambda add-permission --function-name example-function --statement-id apigateway-invoke --action lambda:InvokeFunction --principal apigateway.amazonaws.com --source-arn 'arn:aws:execute-api:{region}:{account_id}:{api_id}/*/GET/example' --region {region}
  • 必须在所有资源、方法和集成配置完成后再创建部署
  • 必须配置请求验证,通过验证QueryString1和HeaderAuth1是否匹配预期模式并强制执行大小限制,拒绝格式错误的查询参数和请求头

6. Deploy the API

6. 部署API

Constraints:
  • You MUST create the deployment with:
    aws apigateway create-deployment --rest-api-id {api_id} --stage-name {stage_name} --region {region}
  • You MUST set the stage variable required by the authorizer with:
    aws apigateway update-stage --rest-api-id {api_id} --stage-name {stage_name} --patch-operations op=replace,path=/variables/StageVar1,value=stageValue1 --region {region}
  • You MUST verify the deployment and stage variable by calling:
    aws apigateway get-stage --rest-api-id {api_id} --stage-name {stage_name} --region {region}
    and confirming StageVar1 is present in the variables
  • You MUST enable access logging on the stage. First create the log group:
    aws logs create-log-group --log-group-name api-gw-access-logs --region {region}
    . Then enable logging with format:
    aws apigateway update-stage --rest-api-id {api_id} --stage-name {stage_name} --patch-operations op=replace,path=/accessLogSettings/destinationArn,value=arn:aws:logs:{region}:{account_id}:log-group:api-gw-access-logs op=replace,path=/accessLogSettings/format,value='{"requestId":"$context.requestId","ip":"$context.identity.sourceIp","requestTime":"$context.requestTime","httpMethod":"$context.httpMethod","resourcePath":"$context.resourcePath","status":"$context.status"}' --region {region}
约束:
  • 必须通过以下命令创建部署:
    aws apigateway create-deployment --rest-api-id {api_id} --stage-name {stage_name} --region {region}
  • 必须通过以下命令设置授权器所需的阶段变量:
    aws apigateway update-stage --rest-api-id {api_id} --stage-name {stage_name} --patch-operations op=replace,path=/variables/StageVar1,value=stageValue1 --region {region}
  • 必须通过以下命令验证部署和阶段变量:
    aws apigateway get-stage --rest-api-id {api_id} --stage-name {stage_name} --region {region}
    ,并确认变量中存在StageVar1
  • 必须在阶段上启用访问日志。首先创建日志组:
    aws logs create-log-group --log-group-name api-gw-access-logs --region {region}
    。然后通过以下格式启用日志:
    aws apigateway update-stage --rest-api-id {api_id} --stage-name {stage_name} --patch-operations op=replace,path=/accessLogSettings/destinationArn,value=arn:aws:logs:{region}:{account_id}:log-group:api-gw-access-logs op=replace,path=/accessLogSettings/format,value='{"requestId":"$context.requestId","ip":"$context.identity.sourceIp","requestTime":"$context.requestTime","httpMethod":"$context.httpMethod","resourcePath":"$context.resourcePath","status":"$context.status"}' --region {region}

7. Create Custom Domain and Base Path Mapping

7. 创建自定义域名和基础路径映射

Constraints:
  • You MUST create the custom domain with:
    aws apigateway create-domain-name --domain-name {custom_domain_name} --regional-certificate-arn {acm_certificate_arn} --endpoint-configuration types=REGIONAL --security-policy TLS_1_2 --region {region}
  • You MUST capture the regionalDomainName and regionalHostedZoneId from the response for use in Step 8
  • You MUST create the base path mapping with:
    aws apigateway create-base-path-mapping --domain-name {custom_domain_name} --rest-api-id {api_id} --stage {stage_name} --base-path '(none)' --region {region}
  • You MUST verify the domain was created by calling:
    aws apigateway get-domain-name --domain-name {custom_domain_name} --region {region}
  • You MUST NOT downgrade the security policy below TLS_1_2
约束:
  • 必须通过以下命令创建自定义域名:
    aws apigateway create-domain-name --domain-name {custom_domain_name} --regional-certificate-arn {acm_certificate_arn} --endpoint-configuration types=REGIONAL --security-policy TLS_1_2 --region {region}
  • 必须从响应中捕获regionalDomainName和regionalHostedZoneId,以便在步骤8中使用
  • 必须通过以下命令创建基础路径映射:
    aws apigateway create-base-path-mapping --domain-name {custom_domain_name} --rest-api-id {api_id} --stage {stage_name} --base-path '(none)' --region {region}
  • 必须通过以下命令验证域名是否创建成功:
    aws apigateway get-domain-name --domain-name {custom_domain_name} --region {region}
  • 不得将安全策略降级到TLS_1_2以下

8. Create Route 53 DNS Record

8. 创建Route 53 DNS记录

Constraints:
  • You MUST create a working copy of
    scripts/dns-record.json
    with placeholders replaced:
    sed -e 's/CUSTOM_DOMAIN_NAME/{custom_domain_name}/' -e 's/REGIONAL_DOMAIN_NAME/{regional_domain_name}/' -e 's/REGIONAL_HOSTED_ZONE_ID/{regional_hosted_zone_id}/' scripts/dns-record.json > /tmp/dns-record.json
  • The command is:
    aws route53 change-resource-record-sets --hosted-zone-id {hosted_zone_id} --change-batch file:///tmp/dns-record.json
  • You MUST use the regionalDomainName and regionalHostedZoneId captured from Step 7, not the user's hosted zone ID for the AliasTarget
  • You MUST use an A-alias record (not CNAME) when using Route 53 as the DNS provider
  • You SHOULD inform the user that DNS propagation can take up to 48 hours
约束:
  • 必须创建
    scripts/dns-record.json
    的工作副本并替换占位符:
    sed -e 's/CUSTOM_DOMAIN_NAME/{custom_domain_name}/' -e 's/REGIONAL_DOMAIN_NAME/{regional_domain_name}/' -e 's/REGIONAL_HOSTED_ZONE_ID/{regional_hosted_zone_id}/' scripts/dns-record.json > /tmp/dns-record.json
  • 使用命令:
    aws route53 change-resource-record-sets --hosted-zone-id {hosted_zone_id} --change-batch file:///tmp/dns-record.json
  • 必须使用步骤7中捕获的regionalDomainName和regionalHostedZoneId,而非用户的托管区域ID作为AliasTarget
  • 当使用Route 53作为DNS提供商时,必须使用A别名记录(而非CNAME)
  • 应告知用户DNS传播可能需要长达48小时

9. Validate Final Setup

9. 验证最终设置

Constraints:
  • You SHOULD run
    scripts/validate.sh {custom_domain_name} {api_id} {region}
    to check all resources
  • You MUST inform the user to test with:
    curl 'https://{custom_domain_name}/example?QueryString1=queryValue1' -H 'HeaderAuth1: headerValue1'
  • You MUST explain that the expected response is a 200 with
    {"message": "Hello from the example function!"}
  • You MUST explain that requests missing the correct HeaderAuth1 header or QueryString1 query parameter will be denied by the authorizer
  • You MUST provide a summary of all created resources including:
    • ACM certificate ARN
    • IAM role ARNs
    • Lambda function ARNs
    • REST API ID and stage name
    • Authorizer ID
    • Custom domain name and Regional domain name
    • Route 53 DNS record
约束:
  • 应运行
    scripts/validate.sh {custom_domain_name} {api_id} {region}
    检查所有资源
  • 必须告知用户使用以下命令进行测试:
    curl 'https://{custom_domain_name}/example?QueryString1=queryValue1' -H 'HeaderAuth1: headerValue1'
  • 必须说明预期响应为200状态码,返回内容为
    {"message": "Hello from the example function!"}
  • 必须说明缺少正确的HeaderAuth1请求头或QueryString1查询参数的请求将被授权器拒绝
  • 必须提供所有已创建资源的摘要,包括:
    • ACM证书ARN
    • IAM角色ARN
    • Lambda函数ARN
    • REST API ID和阶段名称
    • 授权器ID
    • 自定义域名和区域域名
    • Route 53 DNS记录

Examples

示例

Example Input

示例输入

custom_domain_name: api.example.com
region: us-east-2
hosted_zone_id: Z2OJLYMUO9EFXC
stage_name: prod
custom_domain_name: api.example.com
region: us-east-2
hosted_zone_id: Z2OJLYMUO9EFXC
stage_name: prod

Example Output

示例输出

ACM certificate issued for api.example.com
  ARN: arn:aws:acm:us-east-2:123456789012:certificate/abc-123

IAM roles created
  Authorizer: arn:aws:iam::123456789012:role/request-authorizer-role
  Example: arn:aws:iam::123456789012:role/example-function-role

Lambda functions deployed
  Authorizer: arn:aws:lambda:us-east-2:123456789012:function:request-authorizer
  Example: arn:aws:lambda:us-east-2:123456789012:function:example-function

REST API deployed
  API ID: a1b2c3d4e5
  Stage: prod (StageVar1=stageValue1)
  Authorizer: request-authorizer (REQUEST type)

Custom domain configured
  Domain: api.example.com
  Regional endpoint: d-abc123.execute-api.us-east-2.amazonaws.com
  TLS: 1.2

Route 53 DNS record created
  A-alias: api.example.com -> d-abc123.execute-api.us-east-2.amazonaws.com

Test command (authorized):
  curl 'https://api.example.com/example?QueryString1=queryValue1' -H 'HeaderAuth1: headerValue1'

Test command (denied):
  curl 'https://api.example.com/example'
ACM certificate issued for api.example.com
  ARN: arn:aws:acm:us-east-2:123456789012:certificate/abc-123

IAM roles created
  Authorizer: arn:aws:iam::123456789012:role/request-authorizer-role
  Example: arn:aws:iam::123456789012:role/example-function-role

Lambda functions deployed
  Authorizer: arn:aws:lambda:us-east-2:123456789012:function:request-authorizer
  Example: arn:aws:lambda:us-east-2:123456789012:function:example-function

REST API deployed
  API ID: a1b2c3d4e5
  Stage: prod (StageVar1=stageValue1)
  Authorizer: request-authorizer (REQUEST type)

Custom domain configured
  Domain: api.example.com
  Regional endpoint: d-abc123.execute-api.us-east-2.amazonaws.com
  TLS: 1.2

Route 53 DNS record created
  A-alias: api.example.com -> d-abc123.execute-api.us-east-2.amazonaws.com

Test command (authorized):
  curl 'https://api.example.com/example?QueryString1=queryValue1' -H 'HeaderAuth1: headerValue1'

Test command (denied):
  curl 'https://api.example.com/example'

Troubleshooting

故障排除

Certificate Stuck in PENDING_VALIDATION

证书卡在PENDING_VALIDATION状态

Verify the DNS validation CNAME record exists in Route 53 by running
aws acm describe-certificate --certificate-arn {arn} --query 'Certificate.DomainValidationOptions'
. Ensure the CNAME was created in the correct hosted zone.
通过运行
aws acm describe-certificate --certificate-arn {arn} --query 'Certificate.DomainValidationOptions'
验证Route 53中是否存在DNS验证CNAME记录。确保CNAME是在正确的托管区域中创建的。

403 Forbidden on API Calls

API调用返回403 Forbidden

The request authorizer checks three values:
HeaderAuth1
header must be
headerValue1
,
QueryString1
query parameter must be
queryValue1
, and stage variable
StageVar1
must be
stageValue1
. Verify all three are present and correct. Check CloudWatch Logs for the authorizer function for detailed error messages.
请求授权器检查三个值:
HeaderAuth1
请求头必须为
headerValue1
QueryString1
查询参数必须为
queryValue1
,阶段变量
StageVar1
必须为
stageValue1
。验证这三个值是否存在且正确。查看授权器函数的CloudWatch日志获取详细错误信息。

401 Unauthorized

返回401 Unauthorized

API Gateway returns 401 when the authorizer function cannot be invoked. Verify the Lambda permission was added for API Gateway to invoke the authorizer. Check that the authorizer URI is correct.
当无法调用授权器函数时,API Gateway会返回401。验证是否已添加Lambda权限以允许API Gateway调用授权器。检查授权器URI是否正确。

Missing Authentication Token (403)

缺少身份验证令牌(403)

The request path doesn't match a configured resource. Verify the
/example
resource exists with
aws apigateway get-resources --rest-api-id {api_id}
. Ensure the API was deployed after creating all resources.
请求路径与已配置的资源不匹配。通过
aws apigateway get-resources --rest-api-id {api_id}
验证/example资源是否存在。确保在创建所有资源后部署了API。

Custom Domain Returns No Response

自定义域名无响应

DNS propagation can take up to 48 hours. Check with
dig {custom_domain_name}
. Verify the A-alias record points to the correct regionalDomainName and regionalHostedZoneId from the create-domain-name response.
DNS传播可能需要长达48小时。使用
dig {custom_domain_name}
检查。验证A别名记录是否指向create-domain-name响应中的正确regionalDomainName和regionalHostedZoneId。

Stage Variable Not Set

阶段变量未设置

If the authorizer denies all requests, verify the stage variable was set with
aws apigateway get-stage --rest-api-id {api_id} --stage-name {stage_name} --query 'variables'
. The StageVar1 variable must be set to
stageValue1
.
如果授权器拒绝所有请求,通过
aws apigateway get-stage --rest-api-id {api_id} --stage-name {stage_name} --query 'variables'
验证阶段变量是否已设置。StageVar1变量必须设置为
stageValue1

IAM Role Not Found When Creating Lambda

创建Lambda时找不到IAM角色

IAM role propagation is eventually consistent. Wait at least 10 seconds after role creation before creating Lambda functions. Verify the role ARN with
aws iam get-role --role-name {role_name}
.
IAM角色的传播最终是一致的。角色创建后至少等待10秒再创建Lambda函数。通过
aws iam get-role --role-name {role_name}
验证角色ARN。

Base Path Mapping Not Working

基础路径映射不起作用

Verify with
aws apigateway get-base-path-mappings --domain-name {custom_domain_name}
. The base path
(none)
maps the domain root to the stage. Ensure the deployment to the stage completed successfully.
通过
aws apigateway get-base-path-mappings --domain-name {custom_domain_name}
验证。基础路径
(none)
将域名根目录映射到阶段。确保到该阶段的部署已成功完成。

Security Considerations

安全注意事项

  • The hardcoded authorization values (
    headerValue1
    ,
    queryValue1
    ,
    stageValue1
    ) in the Lambda authorizer are for demonstration only and are NOT suitable for production. Replace with proper authentication mechanisms (JWT validation, API keys from AWS Secrets Manager, or OAuth) before deploying to production.
  • Enable request throttling on the API stage to prevent abuse. Configure rate and burst limits with:
    aws apigateway update-stage --rest-api-id {api_id} --stage-name {stage_name} --patch-operations op=replace,path=/throttle/rateLimit,value=1000 op=replace,path=/throttle/burstLimit,value=2000
  • Enable CloudWatch Logs encryption for Lambda log groups. Associate a KMS key with:
    aws logs associate-kms-key --log-group-name /aws/lambda/request-authorizer --kms-key-arn <KMS_KEY_ARN>
  • Protect the public API with AWS WAF to mitigate common exploits (SQL injection, XSS, rate-based rules):
    aws wafv2 associate-web-acl --web-acl-arn <WAF_ACL_ARN> --resource-arn arn:aws:apigateway:{region}::/restapis/{api_id}/stages/{stage_name}
  • Lambda授权器中的硬编码授权值(
    headerValue1
    queryValue1
    stageValue1
    仅用于演示,不适合生产环境。在部署到生产环境前,请替换为适当的身份验证机制(JWT验证、来自AWS Secrets Manager的API密钥或OAuth)。
  • 在API阶段启用请求限流以防止滥用。通过以下命令配置速率和突发限制:
    aws apigateway update-stage --rest-api-id {api_id} --stage-name {stage_name} --patch-operations op=replace,path=/throttle/rateLimit,value=1000 op=replace,path=/throttle/burstLimit,value=2000
  • 为Lambda日志组启用CloudWatch日志加密。通过以下命令关联KMS密钥:
    aws logs associate-kms-key --log-group-name /aws/lambda/request-authorizer --kms-key-arn <KMS_KEY_ARN>
  • 使用AWS WAF保护公共API以缓解常见漏洞(SQL注入、XSS、基于速率的规则):
    aws wafv2 associate-web-acl --web-acl-arn <WAF_ACL_ARN> --resource-arn arn:aws:apigateway:{region}::/restapis/{api_id}/stages/{stage_name}

Additional Resources

附加资源