S3 Bucket中访问被拒绝

时间:2018-04-23 12:35:09

标签: c# amazon-web-services amazon-s3 amazon-cognito

请帮助我正面临问题,我正在尝试访问S3 Bucket Image,我能够列出存储桶项目但是当尝试使用指向的URL在Web应用程序中呈现图像时,我得到 Access否认错误 。我正在使用cognito(联合身份)。

已设置Trust RelationShip

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "",
      "Effect": "Allow",
      "Principal": {
        "Federated": "cognito-identity.amazonaws.com"
      },
      "Action": "sts:AssumeRoleWithWebIdentity",
      "Condition": {
        "StringEquals": {
          "cognito-identity.amazonaws.com:aud": "us-east-1:"
        },
        "ForAnyValue:StringLike": {
          "cognito-identity.amazonaws.com:amr": "unauthenticated"
        }
      }
    }
  ]
}

这是我的完整代码

protected IAmazonEC2 ec2;
        protected IAmazonS3 s3;
        protected IAmazonSimpleDB sdb;
        protected void Page_Load(object sender, EventArgs e) {


            CognitoAWSCredentials credentials = new CognitoAWSCredentials(
    "us-east-1:ox0d70gm-1922z-4772-b2132-9748c6548bdb", // Identity pool ID
    RegionEndpoint.USEast1);


            Console.WriteLine("Identity ID: " + credentials.GetCredentials().Token);
            Console.WriteLine("Identity ID: " + credentials.GetCredentials().UseToken);
            Console.WriteLine("Access Key Id" + credentials.GetCredentials().AccessKey);
            Console.WriteLine("Secret Key:" + credentials.GetCredentials().SecretKey);


            IAmazonS3 s3Client = new AmazonS3Client(credentials);

            try {

                ListBucketsResponse response = s3Client.ListBuckets();

                List<S3Bucket> lS3Bucket = response.Buckets;

                foreach (S3Bucket s3 in lS3Bucket) {
                    Console.WriteLine(s3.BucketName);

                    ListObjectsV2Request request = new ListObjectsV2Request {
                        BucketName = s3.BucketName
                    };

                    ListObjectsV2Response responseV2;

                    responseV2 = s3Client.ListObjectsV2(request);

                    foreach (S3Object entry in responseV2.S3Objects) {

                        if(s3.BucketName== "saveen-2017-june-15") {
                            Response.Write("<img src='https://s3.amazonaws.com/"+ entry.BucketName + "/"+ entry.Key + "' height=100 width=100/>"); // access denied error
                        }
                    }
                }

                int numBuckets = 0;
                if (response.Buckets != null &&
                    response.Buckets.Count > 0) {
                    numBuckets = response.Buckets.Count;
                }
                Console.WriteLine("You have " + numBuckets + " Amazon S3 bucket(s).");
            } catch (AmazonS3Exception ex) {
                if (ex.ErrorCode != null && (ex.ErrorCode.Equals("InvalidAccessKeyId") ||
                    ex.ErrorCode.Equals("InvalidSecurity"))) {
                    Console.WriteLine("Please check the provided AWS Credentials.");
                    Console.WriteLine("If you haven't signed up for Amazon S3, please visit http://aws.amazon.com/s3");
                } else {
                    Console.WriteLine("Caught Exception: " + ex.Message);
                    Console.WriteLine("Response Status Code: " + ex.StatusCode);
                    Console.WriteLine("Error Code: " + ex.ErrorCode);
                    Console.WriteLine("Request ID: " + ex.RequestId);
                }
            }

更新部分

我进一步研究并发现我需要实施 开发人员身份验证身份Authflow(增强型Authflow)

步骤如下:

  1. 通过开发者提供商登录(Amazon Cognito以外的代码)
  2. 验证用户的登录信息(Amazon Cognito以外的代码)
  3. GetOpenIdTokenForDeveloperIdentity
  4. GetCredentialsForIdentity
  5. 以下是上面实施的完整代码

    class Program {
        public static void Main(string[] args) {
    
            //GetOpenIdTokenForDeveloperIdentity
            CognitoAWSCredentials credentials = new CognitoAWSCredentials(
                    "us-east-1:#####-####-####-####-########", RegionEndpoint.USEast1);
    
            //GetCredentialsForIdentity
            GetCredentialsForIdentityResponse tokenResp = identityClient.GetCredentialsForIdentity(credentials.GetIdentityId());
    
            string date = GetRoute53Date();
    
            Console.WriteLine(GetAWSR53_SHA1AuthorizationValue(tokenResp.Credentials.GetCredentials().AccessKey, tokenResp.Credentials.GetCredentials().SecretKey, date));
            // Now here I have Access key and Signature
    
            Console.Read();
        }
    
    
    
        public static string GetAWSR53_SHA1AuthorizationValue(string AWSAccessKeyId,
            string AWSSecretAccessKey, string AmzDate) {
            System.Security.Cryptography.HMACSHA1 MySigner =
               new System.Security.Cryptography.HMACSHA1(
               System.Text.Encoding.UTF8.GetBytes(AWSSecretAccessKey));
    
            string SignatureValue = Convert.ToBase64String(
              MySigner.ComputeHash(System.Text.Encoding.UTF8.GetBytes(AmzDate)));
    
            string AuthorizationValue = "AWS3-HTTPS AWSAccessKeyId=" +
               System.Uri.EscapeDataString(AWSAccessKeyId) +
               ",Algorithm=HmacSHA1,Signature=" + SignatureValue;
    
            return AuthorizationValue;
        }
    
        public static string GetRoute53Date() {
            string url = "https://route53.amazonaws.com/date";
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.Method = "GET";
            HttpWebResponse response;
            response = request.GetResponse() as HttpWebResponse;
            return response.Headers["Date"];
        }
    
    }
    

    现在我正在访问S3存储桶图像资源并希望显示。

    我正在使用以下代码

    GET /####-###-###-15/myfile.png HTTP/1.1
    Host: s3.amazonaws.com
    Authorization: AWS ASIAJ4DZFDVDEB3GSNDA:ulAQKnJkiLAWFg8cB+F+5hje0mE=
    x-amz-date: Thu, 26 Apr 2018 07:14:18 GMT
    Cache-Control: no-cache
    

    它给了我下面给出的错误

    <?xml version="1.0" encoding="UTF-8"?>
    <Error>
        <Code>InvalidAccessKeyId</Code>
        <Message>The AWS Access Key Id you provided does not exist in our records.</Message>
        <AWSAccessKeyId>ASIAJ4DZFDVDEB3GSNDA</AWSAccessKeyId>
        <RequestId>C593C6DE5E004836</RequestId>
        <HostId>fS+WnzQo0UtqlUaLyoMfIxbKElRs56xYPcL8bNn62VQ41HLG26Mr2Aq+2UL6IsZvO1xFxp6lZdc=</HostId>
    </Error>
    

1 个答案:

答案 0 :(得分:3)

如果您尝试使用默认的亚马逊网址,例如https://s3-eu-west-1.amazonaws.com/bucket-name/image.jpg(似乎就是这种情况),这可能是因为默认情况下它们不是从外部公开的。

您必须先将对象设置为“public”,然后才能在Web应用程序中显示它们。

您可以在控制台中执行此操作: Make object public in S3

更改后,在对象属性中,您可以直接访问网址: see here

否则,在尝试访问该URL时,您将收到“访问被拒绝”错误 as here

希望这有帮助!

修改 根据评论,我建议您查看“预签名网址”。 more info。我想这就是你想要实现的目标。在授予客户临时 GET / PUT访问权限的同时保持对象在s3中私有。快乐的编码!