简体   繁体   English

AmazonS3Exception:访问被拒绝

[英]AmazonS3Exception: Access Denied

I trying to connect to s3 bucket to upload/download images. 我试图连接到s3存储桶以上传/下载图像。

My code to create s3 client as follows: 我创建s3客户端的代码如下:

AmazonS3 s3 = AmazonS3ClientBuilder
            .standard()
            .withRegion("EU-WEST-2")
            .build();

I getting exceptions as follows: 我得到如下异常:

com.amazonaws.services.s3.model.AmazonS3Exception: Access Denied (Service: Amazon S3; Status Code: 403; Error Code: AccessDenied; Request ID: 8574612863BD8DC2; S3 Extended Request ID: ueyZy/RLMerNtHeYaOTlRVAqD7w1CksWrjfNLuMgxPWXQbNGDF1Y04RUs4Gh9HeHMwLXxjBc+5o=), S3 Extended Request ID: ueyZy/RLMerNtHeYaOTlRVAqD7w1CksWrjfNLuMgxPWXQbNGDF1Y04RUs4Gh9HeHMwLXxjBc+5o=
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.handleErrorResponse(AmazonHttpClient.java:1630)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeOneRequest(AmazonHttpClient.java:1302)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeHelper(AmazonHttpClient.java:1056)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.doExecute(AmazonHttpClient.java:743)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeWithTimer(AmazonHttpClient.java:717)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.execute(AmazonHttpClient.java:699)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.access$500(AmazonHttpClient.java:667)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutionBuilderImpl.execute(AmazonHttpClient.java:649)
    at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:513)
    at com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:4330)
    at com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:4277)
    at com.amazonaws.services.s3.AmazonS3Client.getObject(AmazonS3Client.java:1410)
    at uk.nhs.digital.cid.pyi.services.paycasso.PaycassoService.registerDocument(PaycassoService.java:80)
    at uk.nhs.digital.cid.pyi.harness.PaycassoClientTestHarness.testVeriSure(PaycassoClientTestHarness.java:61)
    at uk.nhs.digital.cid.pyi.harness.PaycassoClientTestHarness.main(PaycassoClientTestHarness.java:36)

Try this, you need to change env.getProperty("amazon.accessKey") as per your access key and secret. 尝试此操作,您需要根据访问密钥和机密更改env.getProperty(“ amazon.accessKey”)。

public AmazonS3 getAmazonS3Client() {

        ClientConfiguration clientConfig = new ClientConfiguration();
        clientConfig.setProtocol(Protocol.HTTP);
        AmazonS3 s3client = new AmazonS3Client(getAmazonCredentials(), clientConfig);
        s3client.setS3ClientOptions(S3ClientOptions
                .builder()
                .setPathStyleAccess(true)
                .disableChunkedEncoding().build());

        return s3client;
    }

    public AWSCredentials getAmazonCredentials() {
        AWSCredentials credentials = new BasicAWSCredentials(
                env.getProperty("amazon.accessKey"),
                env.getProperty("amazon.secretKey")
        );
        return credentials;
    }

To check bucket exists and upload file check this. 要检查存储桶是否存在并上传文件,请选中此选项。

AmazonS3 s3client = amazonS3ClientService.getAmazonS3Client();
    if (!s3client.doesBucketExistV2(env.getProperty("amazon.bucket"))) {
        System.out.println("Bucket is not Exist.");
        return RepeatStatus.FINISHED;
    }

    // Upload Dir
    TransferManager transferManager = new TransferManager(amazonS3ClientService.getAmazonCredentials());
    MultipleFileUpload upload =
            transferManager.uploadDirectory(env.getProperty("amazon.bucket"), file.getName(), file,true);

if you want to upload a single file then try this, 如果您要上传单个文件,请尝试此操作,

 s3client .putObject(bucket_name, key_name, new File(file_path));

You have two problems. 你有两个问题。

  1. You are using a string for the region. 您正在使用该区域的字符串。 You need to use .withRegion(Regions.EU_WEST_2) . 您需要使用.withRegion(Regions.EU_WEST_2)
  2. From the comments to your question, I understand that you are not using credentials. 从您对问题的评论中,我知道您没有使用凭据。 Even if your bucket is public, you must use AWS credentials to use AWS APIs. 即使您的存储桶是公共的,您也必须使用AWS凭证才能使用AWS API。 Anonymous credentials are not supported. 不支持匿名凭证。

If you want to use anonymous credentials (which means no credentials) use the normal HTTP URL: https://s3.amazonaws.com/bucket/object with a library such as HttpUrlConnection . 如果要使用匿名凭据(这意味着没有凭据),请使用普通的HTTP URL: https://s3.amazonaws.com/bucket/object : HttpUrlConnection以及HttpUrlConnection的库。

In some cases you are allowed to use a string for .withRegion() , but only if the region is not in the Regions enum. 在某些情况下,仅当区域不在Regions枚举中时,才允许将字符串用于.withRegion()

I have tried with this as well 我也尝试过

`AWSCredentials credentials;
    try {
        credentials = new ProfileCredentialsProvider().getCredentials();
    } catch (Exception e) {
        throw new AmazonClientException("Cannot load the credentials from the credential profiles file. "
                + "Please make sure that your correct credentials file is at the correct "
                + "location (/Users/userid/.aws/credentials), and is in valid format.", e);
    }
    AWSSecurityTokenServiceClient stsClient = new AWSSecurityTokenServiceClient(credentials);

    AssumeRoleRequest assumeRequest = new AssumeRoleRequest().withRoleArn(ROLE_ARN).withDurationSeconds(3600)
            .withRoleSessionName("demo");

    AssumeRoleResult assumeResult = stsClient.assumeRole(assumeRequest);

    BasicSessionCredentials temporaryCredentials = new BasicSessionCredentials(
            assumeResult.getCredentials().getAccessKeyId(), assumeResult.getCredentials().getSecretAccessKey(),
            assumeResult.getCredentials().getSessionToken());

s3Client = new AmazonS3Client(temporaryCredentials).withRegion(Regions.EU_WEST_2 )` s3Client = new AmazonS3Client(temporaryCredentials).withRegion(Regions.EU_WEST_2 )`

For your IAM role provide Programmable access, Also in bucket policy give write permission 为您的IAM角色提供可编程访问权限,还可以在存储桶策略中提供写权限

   {
  "Version":"2012-10-17",
  "Statement":[
    {
      "Sid":"mybucketpolicy",
      "Effect":"Allow",
      "Principal": {"Service": "s3.amazonaws.com"},
      "Action":["s3:PutObject"],
      "Resource":["arn:aws:s3:::destination-bucket/*"],
      "Condition": {
          "ArnLike": {
              "aws:SourceArn": "arn:aws:s3:::source-bucket"
           },
         "StringEquals": {
             "aws:SourceAccount": "accid",
             "s3:x-amz-acl": "bucket-owner-full-control"
          }
       }
    }
  ]
}

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

相关问题 AmazonS3Exception与Elasticsearch - AmazonS3Exception with Elasticsearch 为什么我会收到 AmazonS3Exception? - Why am I getting a AmazonS3Exception? AmazonS3Exception:仅在Linux远程服务器中请求签名错误? - AmazonS3Exception: request signature error only in linux remote server? AmazonS3Exception:授权 header 格式错误; 该地区是错误的 - AmazonS3Exception: The authorization header is malformed; the region is wrong com.amazonaws.services.s3.model.AmazonS3Exception:访问被拒绝 - com.amazonaws.services.s3.model.AmazonS3Exception: Access Denied 为什么在使用 PutObjectRequest 时 putObject 会抛出 AmazonS3Exception,但在没有 PutObjectRequest 的情况下工作正常? - why does putObject throw AmazonS3Exception when using PutObjectRequest, but works fine without PutObjectRequest? 如何解决 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 AmazonS3 SDK:列出对象时拒绝访问 - AmazonS3 SDK: Access denied when Listing Objects 访问控制异常-访问被拒绝 - Access Control Exception - Access Denied Spring-处理访问被拒绝的异常 - Spring - handling access denied exception
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM