AWS S3 Java 开发工具包 - 拒绝访问

2022-09-01 13:05:38

我正在尝试使用AWS开发工具包访问存储桶及其所有对象,但在运行代码时,我在线程“main”中收到异常错误com.amazonaws.services.s3.model.AmazonS3Exception: Access Denied (Service: Amazon S3; Status Code: 403; Error Code: AccessDenied; Request ID: X), S3 Extended Request ID: Y=

请建议,我缺少的地方以及为什么发生访问被拒绝错误,尽管我已经对存储桶采取了以下所有权限:

s3:GetObject
s3:GetObjectVersion
s3:GetObjectAcl
s3:GetBucketAcl
s3:GetBucketCORS
s3:GetBucketLocation
s3:GetBucketLogging
s3:ListBucket
s3:ListBucketVersions
s3:ListBucketMultipartUploads
s3:GetObjectTorrent
s3:GetObjectVersionAcl

代码如下:

AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
ClientConfiguration clientConfig = new ClientConfiguration();
clientConfig.setProtocol(Protocol.HTTP);
AmazonS3 conn = new AmazonS3Client(credentials, clientConfig);
conn.setEndpoint(bucketName);
Bucket bucket = conn.createBucket(bucketName);
ObjectListing objects = conn.listObjects(bucket.getName());
do {
    for (S3ObjectSummary objectSummary : objects.getObjectSummaries()) {
            System.out.println(objectSummary.getKey() + "\t" +
                    objectSummary.getSize() + "\t" +
                    StringUtils.fromDate(objectSummary.getLastModified()));
    }
    objects = conn.listNextBatchOfObjects(objects);
} while (objects.isTruncated());

答案 1

转到 IAM 并检查用于 API 的用户 [ 访问密钥 & 私有密钥 ] 是否具有使用基于 S3 的 API 的预授权。

已将 S3 策略附加到指定用户 - 尝试使用 S3 完全访问权限;一旦这有效,您就可以对访问进行细粒度处理。有关更多信息,请查看此链接 [ 管理 IAM 策略 ]


答案 2

问题现在已经解决。代码存在以下问题:

  1. 终点不正确,应该有正确的终点。
  2. 没有为存储桶授予足够的权限。在 AWS 开发工具包中使用存储桶之前,应获取完整权限的列表。

以下是正确的代码

AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
ClientConfiguration clientConfig = new ClientConfiguration();
clientConfig.setProtocol(Protocol.HTTP);
AmazonS3 conn = new AmazonS3Client(credentials, clientConfig);
conn.setEndpoint("correct end point");
Bucket bucket = conn.createBucket(bucketName);
ObjectListing objects = conn.listObjects(bucket.getName());
do {
    for (S3ObjectSummary objectSummary : objects.getObjectSummaries()) {
            System.out.println(objectSummary.getKey() + "\t" +
                    objectSummary.getSize() + "\t" +
                    StringUtils.fromDate(objectSummary.getLastModified()));
    }
    objects = conn.listNextBatchOfObjects(objects);
} while (objects.isTruncated());

推荐