使用 AWS CDK,可以通过以下步骤来创建一个 API Gateway 并导入证书,并启用 MTLS 所有权验证证书:
首先,确保你已经安装了 AWS CDK,并在项目中初始化了 CDK。
在 CDK 项目的根目录中创建一个新的文件(比如 api-stack.ts
),用于定义 API Gateway 的堆栈。
在 api-stack.ts
文件中导入所需的 CDK 模块和 AWS SDK 模块:
import * as cdk from 'aws-cdk-lib';
import * as apigw from 'aws-cdk-lib/aws-apigateway';
import * as acm from 'aws-sdk/clients/acm';
cdk.Stack
,用于定义 API Gateway 的堆栈:export class ApiStack extends cdk.Stack {
constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
// 创建 API Gateway
const apiGateway = new apigw.RestApi(this, 'MyApi', {
// 添加其他配置选项
// ...
});
// 导入证书
const certificateArn = 'YOUR_CERTIFICATE_ARN'; // 替换为实际的证书 ARN
const certificateId = certificateArn.split('/')[1]; // 从 ARN 中提取证书 ID
const acmClient = new acm({ region: 'YOUR_REGION' }); // 替换为实际的区域
const certificate = await acmClient.describeCertificate({ CertificateArn: certificateArn }).promise();
// 创建 API Gateway 部署
const deployment = new apigw.Deployment(this, 'Deployment', {
api: apiGateway,
});
// 创建 API Gateway 资源
const resource = apiGateway.root.addResource('my-resource');
// 创建 API Gateway 方法
const method = resource.addMethod('GET', new apigw.LambdaIntegration(myLambdaFunction));
// 添加 MTLS 配置
method.addRequestValidator('mtls-validator', {
requestValidatorName: 'MTLSValidator',
validateRequestBody: true,
validateRequestParameters: true,
});
method.addRequestParameter('x-amzn-apigateway-mtls-client-certificate', 'method.request.header.x-amzn-apigateway-mtls-client-certificate', {
required: true,
mapping: apigw.MappingType.HEADER,
});
method.addRequestParameter('x-amzn-apigateway-mtls-client-certificate-arn', 'method.request.header.x-amzn-apigateway-mtls-client-certificate-arn', {
required: true,
mapping: apigw.MappingType.HEADER,
});
method.addRequestParameter('x-amzn-apigateway-mtls-authentication', 'method.request.header.x-amzn-apigateway-mtls-authentication', {
required: true,
mapping: apigw.MappingType.HEADER,
});
method.addRequestParameter('x-amzn-apigateway-mtls-authentication-arn', 'method.request.header.x-amzn-apigateway-mtls-authentication-arn', {
required: true,
mapping: apigw.MappingType.HEADER,
});
// 更新 API Gateway 部署
deployment.node.addDependency(method);
}
}
请注意,上述代码中的 'YOUR_CERTIFICATE_ARN'
和 'YOUR_REGION'
需要替换为实际的证书 ARN 和区域。
main.ts
或 app.ts
文件中,创建一个 CDK App 并实例化堆栈:import * as cdk from 'aws-cdk-lib';
import { ApiStack } from './api-stack';
const app = new cdk.App();
new ApiStack(app, 'ApiStack');
cdk deploy
命令来部署堆栈。以上代码示例中,我们使用 aws-sdk
的 acm
客户端来获取证书的详细信息。然后,我们通过 API Gateway 的 addRequestParameter
方法来添加 MTLS 相关的请求参数,并使用 addRequestValidator
方法来启用 MTLS 验证。
请确保你已经正确配置了 AWS CLI,以便能够通过