简体   繁体   中英

AmazonS3Exception: Access Denied

I trying to connect to s3 bucket to upload/download images.

My code to create s3 client as follows:

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.

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) .
  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. 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 .

In some cases you are allowed to use a string for .withRegion() , but only if the region is not in the Regions enum.

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 )`

For your IAM role provide Programmable access, Also in bucket policy give write permission

   {
  "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"
          }
       }
    }
  ]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM