创建可以使用CDK读取非公共S3存储桶的API网关



我正在尝试使用CDK创建一个可以访问非公共S3存储桶的代理API网关。为此,我创建了一个角色:

const role = new iam.Role(this, 'apigw-s3-readonly-role', {
roleName: 'ApiGw-S3-ReadOnly',
assumedBy: new iam.ServicePrincipal('apigateway.amazonaws.com'),
})
role.addToPolicy(new iam.PolicyStatement({
resources: [bucket.bucketArn],
actions: ['s3:GetObject']
}))

并创建了一个类似这样的API:

const api = new apigw.RestApi(this, 'TestApi')
api.root
.addResource('{file}')
.addMethod('GET', new apigw.AwsIntegration({
service: 's3',
integrationHttpMethod: 'GET',
path: 'my-test-bucket/{file}',
options: {
credentialsRole: role,
requestParameters: {
'integration.request.path.file': 'method.request.path.file'
},
integrationResponses: [{
statusCode: "200"
}]
}
}), {
requestParameters: {
'method.request.path.file': true
}
})

但这需要S3 bucket public。我认为这是因为它向S3发送http请求,但我只允许s3:GetObject担任该角色。

因此,我如何更改API网关以允许在不公开S3桶对象的情况下访问它们。

我尝试了下面的代码,因为它声明了操作GetObject,所以看起来很有希望,但它不起作用。

api.root
.addResource('{file}')
.addMethod('GET', new apigw.AwsIntegration({
service: 's3',
action: 'GetObject',
actionParameters: {
Bucket: 'my-test-bucket',
Key: 'file'
},
...

您的策略有问题。GetObject权限应该应用于对象,而不是应用于bucket。

role.addToPolicy(new iam.PolicyStatement({
resources: [`${bucket.bucketArn}/*`],
actions: ['s3:GetObject']
}))

最新更新