0

I am new to AWS Service, I am doing some R&D on IAM. I created one IAM user and IAM role(with Full S3 Read permission) and attach that IAM User with Role. I am using Spring boot application trying to connect that bucket with IAM user using STS assume Role. But I am getting below error:

om.amazonaws.services.s3.model.AmazonS3Exception: The AWS Access Key Id you provided does not exist in our records. (Service: Amazon S3; Status Code: 403; Error Code: InvalidAccessKeyId; Request ID: 15G2FVKSWVYQNXXXX;
and I have verified that secretkey and access key are correct. may by the access key. @Note: S3 bucket/IAM user/IAM role are in same aws account.

I know we can directly attach policy to user and fetch the bucket, but I want to try with assume role in same account. below is my code snippet:

public static void main(String[] args) {
        try{

            AWSSecurityTokenService stsclient= AWSSecurityTokenServiceClientBuilder.standard()
                .withCredentials(new AWSStaticCredentialsProvider(getAWSCredentials("AKIAWEBTXXXXXXEDTIGNM", "KJR1e6eqk7schchdjhdyIf8R2FJQ6i")))
                .withRegion(Regions.fromName("us-west-2"))
                .build();
            

            AssumeRoleRequest roleRequest= new AssumeRoleRequest().withDurationSeconds(3600).withRoleArn("arn:aws:iam::421XXXXX2511:role/s3_readonly_access_role").withRoleSessionName("test-session");
            AssumeRoleResult roleResult=stsclient.assumeRole(roleRequest);
            Credentials creds= roleResult.getCredentials();
            AWSStaticCredentialsProvider credProvider= new AWSStaticCredentialsProvider(new BasicSessionCredentials(creds.getAccessKeyId(),creds.getSecretAccessKey(),creds.getSessionToken()));
            
            AmazonS3 s3=AmazonS3ClientBuilder
                .standard()
                .withCredentials(new AWSStaticCredentialsProvider(getAWSCredentials(credProvider.getCredentials().getAWSAccessKeyId(),credProvider.getCredentials().getAWSSecretKey())))
                .withRegion(Regions.fromName("us-west-2"))
                .build();

            List<Bucket> buckets=   s3.listBuckets();
            for(Bucket bucket:buckets){
                System.out.println(bucket.getName());
            }
        }catch(AmazonS3Exception ex){
            ex.printStackTrace();
        }
    }

    private static AWSCredentials getAWSCredentials(String accessKey, String secretKey) {
        return new BasicAWSCredentials(
                accessKey,
                secretKey);
    }

Sanjay
  • 89
  • 1
  • 13
  • Which line is generating the error? – John Rotenstein Jul 19 '23 at 09:59
  • **Side-note:** You should never need to provide your credentials in the code itself. Instead, you can store them in a credentials file. The easiest way to do this is to run the AWS CLI `aws configure` command. Then, your code will automatically use those stored credentials. – John Rotenstein Jul 19 '23 at 10:02
  • 2
    The `.withCredentials(new AWSStaticCredentialsProvider(getAWSCredentials(credProvider.getCredentials().getAWSAccessKeyId(),credProvider.getCredentials().getAWSSecretKey())))` is missing the session token. Overall you are doing **waaaay too much** credential handling here. See e.g. https://stackoverflow.com/questions/48789429/assume-role-with-spring-cloud-aws-autoconfiguration how to properly pass the credentials from STS to the S3 client. – luk2302 Jul 19 '23 at 10:05
  • @JohnRotenstein at List buckets= s3.listBuckets(); line i am getting this error. – Sanjay Jul 19 '23 at 10:37
  • You are using V1 - which is NOT best practice. See my answer. – smac2020 Jul 19 '23 at 13:41

1 Answers1

2

We have this exact use case as part of the AWS Code Library - which uses AWS SDK for Java v2. V1 is NOT recommended to use anymore as specified here in this AWS page.

This example shows you how to perform these tasks:

  1. Creates a user that has no permissions.
  2. Creates a role and policy that grants Amazon S3 permissions.
  3. Creates a role.
  4. Grants the user permissions.
  5. Gets temporary credentials by assuming the role. Creates an Amazon S3 Service client object with the temporary credentials.
  6. Deletes the resources.

Follow this example.

Create an IAM user and assume a role with AWS STS using an AWS SDK

If you prefer to see it in Github -- see:

https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javav2/example_code/iam/src/main/java/com/example/iam/IAMScenario.java

smac2020
  • 9,637
  • 4
  • 24
  • 38