简体   繁体   English

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

[英]get HTTP/1.1 403 Forbidden when trying to access private content stored in S3(static web hosting) using cloudfront and privateKey

I am receiving following response from AWS CloudFront from Java application where I am trying to access a private content (web page) using signed cookies. 我收到来自Java应用程序的AWS CloudFront的以下响应,该应用程序试图使用签名的cookie访问私有内容(网页)。

HTTP/1.1 403 Forbidden [Content-Type: application/xml, Transfer-Encoding: chunked, Connection: keep-alive, Date: Fri, 23 Aug 2019 12:47:53 GMT, Server: AmazonS3, X-Cache: Error from cloudfront, Via: 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 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

I tried the following steps: 我尝试了以下步骤:

  1. I have configured an S3 bucked as "Static website hosting" 我已将S3配置为“静态网站托管”
  2. set the bucket policy as : 将存储桶策略设置为:
{
    "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/*"
        }
    ]
}
  1. CORS configuration of the bucket as : 存储桶的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>
  1. create a CloudFront distribution with: 使用以下方法创建CloudFront分配:

    • Origin Settings -> Origin Domain Name: my-s3-bucket-name 原始设置->原始域名:my-s3-bucket-name
    • Origin Settings -> Restrict Bucket Access: yes 原始设置->限制存储区访问:是
    • Restrict Viewer Access(Use Signed URLs or Signed Cookies): yes. 限制查看者访问(使用签名的URL或签名的Cookie):是。
    • Trusted Signers: self(checked). 受信任的签名者:自我(选中)。
    • leave rest of the properties default. 将其余属性保留为默认值。
  2. Created security credential under (CloudFront key pairs) and downloaded the private key. 在(CloudFront密钥对)下创建了安全凭证,并下载了私钥。 convert the .pem file into .der using the following command. 使用以下命令将.pem文件转换为.der。

openssl pkcs8 -topk8 -nocrypt -in origin.pem -inform PEM -out new.der -outform DER 
  1. created a Maven project with the following dependencies: 创建了一个具有以下依赖项的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>
  1. the code is as below trying to access "index.html" file (saved in S3 the root directory) using signed cookies: 代码如下,尝试使用签名的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();
    }

}

  1. And I have received 403 response. 而且我已经收到403的回复。

How can I fix this issue? 如何解决此问题?

please first read my last comment under my first post. 请先阅读我在第一篇文章中的最后评论。 this part is related to the previous post. 这部分与上一篇文章有​​关。 here is the code sample I used to sign the URL with signUrlCanned and get the content but when I tried to use buildPolicyForSignedUrl got access denied error. 这是我用来用signUrlCanned签名URL并获取内容的代码示例,但是当我尝试使用buildPolicyForSignedUrl时,访问被拒绝错误。

@JamesDean: thanks for your comments. @JamesDean:感谢您的评论。 In the above example. 在上面的例子中。 I choose Origin Domain Name from the drop-down (as s3 bucket) and used OAI where I used S3 was configured as a static website, which was my first mistake. 我从下拉列表中选择“原始域名”(作为s3存储桶),并使用OAI(其中我将S3配置为静态网站),这是我的第一个错误。 Anyway, I resolved this by providing a custom origin name (static website endpoint URL). 无论如何,我通过提供自定义来源名称(静态网站端点网址)解决了此问题。 Then tested without enabling "Use Signed URLs or Signed Cookies", and worked without any issue. 然后在未启用“使用签名的URL或签名的Cookie”的情况下进行了测试,并且可以正常工作。 but if I enable "Use Signed URLs or Signed Cookies" and tried to use Signed URL or Signed cookies got the 403 error which I could not solve yet. 但是如果启用“使用签名的URL或签名的cookie”并尝试使用签名的URL或签名的cookie,则会收到403错误,但我无法解决。 I am providing the code sample below if you can help me anyway. 如果您仍然可以帮助我,我将在下面提供代码示例。

using following code I get the correct signed url and can access the content: 使用以下代码,我可以获得正确的签名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);

On the other hand, when I tried to access the content using a custom policy for the same s3 content (index.html in the root) I got access denied: 另一方面,当我尝试使用针对相同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);

The response I received: 我收到的回复:


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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 Cloudfront 签名 cookie 时出现 403 禁止错误? - 403 Forbidden error using Cloudfront signed cookies? 登录失败:禁止403; 尝试使用Netbeans(使用Amazon API)访问Eucalyptus Cloud时 - Login failure : 403 forbidden; When trying to access the Eucalyptus Cloud Using Netbeans(with Amazon API) 使用AWS Java SDK拒绝访问由链接到私有S3存储桶的Amazon CloudFront的安全签名URL提供的图像 - Access denied to images served by secure signed URLs of Amazon CloudFront linked to private S3 bucket using AWS Java SDK 尝试使用CORS时获取403(禁止) - Getting 403 (Forbidden) when trying to use CORS AWS S3 Java:d​​osObjectExist结果为403:禁止 - AWS S3 Java: doesObjectExist results in 403: FORBIDDEN 如何解决 AmazonS3Exception: Forbidden (Service: Amazon S3; Status Code: 403; Error Code: 403 Forbidden; Request ID: null) 使用 java - How to resolve AmazonS3Exception: Forbidden (Service: Amazon S3; Status Code: 403; Error Code: 403 Forbidden; Request ID: null) using java 当使用NTLM对Sharepoint使用HttpClient身份验证机制时,HTTP 403禁止使用 - HTTP 403 Forbidden coming when using HttpClient authentication mechanism for Sharepoint using NTLM 将内容上传到 AWS S3 并通过 Cloudfront 提供内容 - Upload content to AWS S3 and serve the content via Cloudfront 无法使用 http:// 连接到 phpmyadmin<ip-address> :port 禁止 403 - Can't connect to phpmyadmin using http://<ip-address>:port get 403 forbidden 当我在谷歌 kubernetes 引擎上运行我的应用程序时,我得到 org.springframework.web.client.HttpClientErrorException$Forbidden: 403 Forbidden 错误 - When I run my application on google kubernetes engine, i get org.springframework.web.client.HttpClientErrorException$Forbidden: 403 Forbidden error
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM