尝试使用cloudfront和privateKey尝试访问存储在S3(静态网络托管)中的私有(private)内容时,获得HTTP / 1.1 403禁止

2020年5月14日 12点热度 0条评论

我收到来自Java应用程序的AWS CloudFront的以下响应,该应用程序试图使用签名的cookie访问私有内容(网页)。

HTTP / 1.1 403禁止[内容类型:application / xml,传输编码:分块,连接:keep-alive,日期:Fri,23 Aug 2019 12:47:53 GMT,服务器:AmazonS3,X-Cache:来自cloudfront,通过:1.1 1b964435 *********** d975cdd ***。cloudfront.net(CloudFront),X-Amz-Cf-Pop:MXP64-C1,X-Amz-Cf-Id:6Waw **** _ ukbfaev1nrJZZYBl ********** t66R9ctZ ***** A ==] org.apache.http.conn.BasicManagedEntity@5fdba6f9

我尝试了以下步骤:

我已将S3配置为“静态网站托管”
将存储桶策略设置为:

{
    "Version": "2012-10-17",
    "Statement": [
          {
            "Sid": "2",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity E1J***SIQ****"
            },
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::my-xxxxx-s3-bucket/*"
        }
    ]
}

存储桶的CORS配置为:

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedMethod>HEAD</AllowedMethod>
    <MaxAgeSeconds>3000</MaxAgeSeconds>
    <AllowedHeader>Authorization</AllowedHeader>
</CORSRule>
</CORSConfiguration>

使用以下方法创建CloudFront分配:

原始设置->原始域名:my-s3-bucket-name

原始设置->限制存储桶访问:是

限制查看者访问(使用签名的URL或签名的Cookie):是。

受信任的签名者:自我(选中)。

将其余属性保留为默认值。

在(CloudFront密钥对)下创建了安全凭证,并下载了私钥。使用以下命令将.pem文件转换为.der。

openssl pkcs8 -topk8 -nocrypt -in origin.pem -inform PEM -out new.der -outform DER 

创建了一个具有以下依赖项的Maven项目:

<dependencies>
  <dependency>
    <groupId>com.amazonaws</groupId>
    <artifactId>aws-java-sdk</artifactId>
    <version>1.11.327</version>
  </dependency>

    <!-- https://mvnrepository.com/artifact/org.bouncycastle/bcprov-jdk15on -->
<dependency>
    <groupId>org.bouncycastle</groupId>
    <artifactId>bcprov-jdk15on</artifactId>
    <version>1.62</version>
</dependency>

<!-- https://mvnrepository.com/artifact/net.java.dev.jets3t/jets3t -->
<dependency>
    <groupId>net.java.dev.jets3t</groupId>
    <artifactId>jets3t</artifactId>
    <version>0.9.4</version>
</dependency>

代码如下,尝试使用签名的cookie访问“ index.html”文件(在S3中保存在根目录中):

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.spec.InvalidKeySpecException;
import java.text.ParseException;
import java.util.Date;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.jets3t.service.CloudFrontServiceException;

import com.amazonaws.services.cloudfront.CloudFrontCookieSigner;
import com.amazonaws.services.cloudfront.CloudFrontCookieSigner.CookiesForCustomPolicy;
import com.amazonaws.services.cloudfront.util.SignerUtils;
import com.amazonaws.services.cloudfront.util.SignerUtils.Protocol;
import com.amazonaws.util.DateUtils;

public class SignedCookies {

    public static void withCustom() throws InvalidKeySpecException, IOException{

        Protocol protocol = Protocol.http;
        String resourcePath = "index.html";
        String distributionDomain = "***ju***lu***.cloudfront.net";
        String privateKeyFilePath = "my-path/pk-APKA####K3WH####7U##.der";
        File privateKeyFile = new File(privateKeyFilePath);
        String s3ObjectKey = "index.html";
        String keyPairId = "APKA####K3WH####7U##";


         Date activeFrom = DateUtils.parseISO8601Date("2018-11-14T22:20:00.000Z");
         Date expiresOn = DateUtils.parseISO8601Date("2020-11-14T22:20:00.000Z");
         String ipRange = null;

         CookiesForCustomPolicy cookies = CloudFrontCookieSigner.getCookiesForCustomPolicy(
                      protocol, distributionDomain, privateKeyFile, s3ObjectKey,
                      keyPairId, expiresOn, activeFrom, ipRange);


         @SuppressWarnings({ "resource", "deprecation" })
        HttpClient client = new DefaultHttpClient();
         HttpGet httpGet = new HttpGet(
                      SignerUtils.generateResourcePath(protocol, distributionDomain,
                      resourcePath));

         httpGet.addHeader("Cookie", "Secure");
         httpGet.addHeader("Cookie", cookies.getPolicy().getKey() + "=" +
             cookies.getPolicy().getValue());
         httpGet.addHeader("Cookie", cookies.getSignature().getKey() + "=" +
             cookies.getSignature().getValue());
         httpGet.addHeader("Cookie", cookies.getKeyPairId().getKey() + "=" +
             cookies.getKeyPairId().getValue());


         HttpResponse response = client.execute(httpGet);

         System.out.println(response.toString());

    }

    public static void main(String[] args) throws FileNotFoundException, IOException, CloudFrontServiceException, ParseException, InvalidKeySpecException {
        withCustom();
    }

}

而且我已经收到403的回复。

如何解决此问题?

解决方案如下:

请先阅读我在第一篇文章中的最后评论。这部分与上一篇文章有​​关。这是我用来使用signUrlCanned签名URL并获取内容的代码示例,但是当我尝试使用buildPolicyForSignedUrl时,访问被拒绝错误。

@JamesDean:感谢您的评论。在上面的例子中。我选择
下拉列表中的原始域名(作为s3存储桶)和使用的OAI
我使用S3的地方被配置为静态网站,这是我的第一个
错误。无论如何,我通过提供自定义来源名称解决了此问题
(静态网站端点URL)。然后在未启用“使用
签名的URL或签名的Cookie”,并且没有任何问题。但是,如果我
启用“使用签名的URL或签名的Cookie”并尝试使用签名的URL
或签名的Cookie收到了403错误,但我无法解决。我是
如果您仍然可以帮助我,请提供以下代码示例。

使用以下代码,我可以获得正确的签名URL,并且可以访问内容:

byte[] derPrivateKey = EncryptionUtil.convertRsaPemToDer(new FileInputStream(privateKeyFilePath));
//      Generate a "canned" signed URL to allow access to a specific distribution and object

        String signedUrlCanned = CloudFrontService.signUrlCanned(
            "https://" + distributionDomain + "/" + s3ObjectKey, // Resource URL or Path
            keyPairId,     // Certificate identifier, an active trusted signer for the distribution
            derPrivateKey, // DER Private key data
            ServiceUtils.parseIso8601Date("2020-08-30T22:20:00.000Z") // DateLessThan
            );
        System.out.println(signedUrlCanned);

另一方面,当我尝试使用针对相同s3内容(根目录中的index.html)的自定义策略访问内容时,访问被拒绝:

String policyResourcePath = distributionDomain + "/*" ;
//      Convert an RSA PEM private key file to DER bytes

        byte[] derPrivateKey = EncryptionUtil.convertRsaPemToDer(new FileInputStream(privateKeyFilePath));

        String policy = CloudFrontService.buildPolicyForSignedUrl(
                policyResourcePath, // Resource path (optional, may include '*' and '?' wildcards)
                ServiceUtils.parseIso8601Date("2020-11-14T22:20:00.000Z"), // DateLessThan
                "0.0.0.0/0", // CIDR IP address restriction (optional, 0.0.0.0/0 means everyone)
                ServiceUtils.parseIso8601Date("2017-10-16T06:31:56.000Z")  // DateGreaterThan (optional)
                );

        String signedUrl = CloudFrontService.signUrl(
                "https://" + distributionDomain + "/" + s3ObjectKey, // Resource URL or Path
                keyPairId,     // Certificate identifier, an active trusted signer for the distribution
                derPrivateKey, // DER Private key data
                policy // Access control policy
                );
            System.out.println(signedUrl);

我收到的回复:


<?xml version="1.0" encoding="UTF-8"?>
<Error>
    <Code>AccessDenied</Code>
    <Message>Access denied</Message>
</Error>

代码参考:
https://jets3t.s3.amazonaws.com/toolkit/code-samples.html