Java amazonS3.generatePresignedUrl - 如何配置 https://s3.amazonaws.com/mycompany 而不是 https://mycompany.s3.amazonaws.com/com.mycompany

Java amazonS3.generatePresignedUrl - How to configure https://s3.amazonaws.com/mycompany instead of https://mycompany.s3.amazonaws.com/com.mycompany

我们正在使用预签名的 s3 urls 来提供对存储在 s3 中的图像的 Web 访问。

我们用来生成预签名 url 的 java 代码类似于下面的

String accessKey = ...;
String secretKey = ...;
String region = ...;
com.amazonaws.HttpMethod awsHttpMethod = ...;
String bucketName = ...;
String objectKey = ...;
Date expirationDate = ...;

BasicAWSCredentials creds = new BasicAWSCredentials(accessKey, secretKey);
AmazonS3 s3Client = AmazonS3ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(creds)).withRegion(region).build();
GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucketName, objectKey);
generatePresignedUrlRequest.setMethod(awsHttpMethod);
generatePresignedUrlRequest.setExpiration(expirationDate);
URL url = s3Client.generatePresignedUrl(generatePresignedUrlRequest);

代码生成的 url 看起来类似于

https://com.mycompany.personalpictures.s3.amazonaws.com/picture123.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20170623T150540Z&X-Amz-SignedHeaders=host&X-Amz-Expires=59&X-Amz-Credential=AKIAIVLB4ANK6B45G3IA%2F20170623%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Signature=d25d407ee8efa76f339388ec93579a19be8eaead9663d6d378cf2ec6d9d9cac2

然而,由于我们的存储桶命名标准包含点,因此调用上述 URL 会导致 SSL: no alternative certificate subject name matches target host name 'com.mycompany.personalpictures.s3.amazonaws.com' 错误

我看了this post that the root cause is the dots in the bucket name and that using https://s3.amazonaws.com/com.mycompany.personalpictures/picture123.png应该可以绕过这个问题。

如何使用 url 格式 https://s3.amazonaws.com/mybucket/myfile 生成预签名的 url?

想通了...

创建s3客户端时需要使用.enablePathStyleAccess()。现在代码行是

AmazonS3 s3Client = AmazonS3ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(creds)).withRegion(region).enablePathStyleAccess().build();