How can I use the assumed role in AWS STS to grant temporary access to the S3 bucket?

258    Asked by DominicPoole in AWS , Asked on May 30, 2024

I am currently working as a cloud security Engineer for a particular company that has multiple AWS accounts for different departments. The finance department has its own AWS account with the specific IAM role and also the policies to access financial data. A user from the IT department needs temporary access to a specific S3 bucket in the account if the finance department for a one-time data analysis task. How can I use the assumed role in AWS STS to grant temporary access to the IT user? 

Answered by Connor Peake

 In the context of AWS, here are the steps given:-

Create an IAM role in the financial account

Firstly, you would need to log in to the AWS management console of the financial account. Now you should navigate to the IAM user service and there you can create a new role. Now you would need to create “Another AWS account”. Now enter the IT account AWS account ID.

Allow the IT account to assume the role

Still, in the financial account, you should edit the trust relationship of the new code to allow the IT account to assume it.

Assume the role in the IT account

In the IT account, the users should have an IAM role or even a user with the appropriate permissions for calling the “sts.Assumerole”.

Here is the combined coding for assuming a role and then accessing the S3 bucket by using Python with Boto3:-

Import boto3
# Define the AWS accounts and role ARNs
Finance_account_id = ‘your-finance-account-id’
It_account_id = ‘your-it-account-id’
Finance_role_arn = f’arn:aws:iam::{finance_account_id}:role/FinanceS3AccessRole’
It_role_arn = f’arn:aws:iam::{it_account_id}:role/ITUserRole’
Bucket_name = ‘finance-bucket-name’
# Assume the role in the finance account
Sts_client = boto3.client(‘sts’)
Assumed_role = sts_client.assume_role(
    RoleArn=finance_role_arn,
    RoleSessionName=’ITAccessToFinanceS3’
)
# Extract temporary credentials
Credentials = assumed_role[‘Credentials’]
Access_key = credentials[‘AccessKeyId’]
Secret_key = credentials[‘SecretAccessKey’]
Session_token = credentials[‘SessionToken’]
# Create an S3 client with temporary credentials
S3_client = boto3.client(
    ‘s3’,
    Aws_access_key_id=access_key,
    Aws_secret_access_key=secret_key,
    Aws_session_token=session_token
)
# List objects in the S3 bucket
Response = s3_client.list_objects_v2(Bucket=bucket_name)
For obj in response.get(‘Contents’, []):
    Print(obj[‘Key’])

Here is an example given of how you can assume an IAM role by using the AWS SDK for the java programming language and then access an S3 bucket by using the assume role Credentials:-

Import software.amazon.awssdk.auth.credentials.AwsSessionCredentials;
Import software.amazon.awssdk.regions.Region;
Import software.amazon.awssdk.services.sts.StsClient;
Import software.amazon.awssdk.services.sts.model.AssumeRoleRequest;
Import software.amazon.awssdk.services.s3.S3Client;
Import software.amazon.awssdk.services.s3.model.ListObjectsV2Request;
Import software.amazon.awssdk.services.s3.model.ListObjectsV2Response;
Import software.amazon.awssdk.services.s3.model.S3Object;
Public class AssumeRoleExample {
    Public static void main(String[] args) {
        String roleArn = “arn:aws:iam::finance-account-id:role/FinanceS3AccessRole”;
        String bucketName = “finance-bucket-name”;
        // Assume role and get temporary credentials
        AwsSessionCredentials credentials = assumeRole(roleArn);
        // Use the temporary credentials to access S3
        S3Client s3Client = S3Client.builder()
                .region(Region.US_EAST_1) // Update with your bucket’s region
                .credentialsProvider(() -> credentials)
                .build();
        ListObjectsV2Request listRequest = ListObjectsV2Request.builder()
                .bucket(bucketName)
                .build();
        ListObjectsV2Response listResponse = s3Client.listObjectsV2(listRequest);
        For (S3Object s3Object : listResponse.contents()) {
            System.out.println(“Object Key: “ + s3Object.key());
        }
    }
    Private static AwsSessionCredentials assumeRole(String roleArn) {
        StsClient stsClient = StsClient.builder().build();
        AssumeRoleRequest assumeRequest = AssumeRoleRequest.builder()
                .roleArn(roleArn)
                .roleSessionName(“AssumedRoleSession”)
                .build();
        AwsSessionCredentials sessionCredentials = stsClient.assumeRole(assumeRequest)
                .credentials()
                .toBuilder()
                .build();
        Return sessionCredentials;
    }
}


Your Answer

Interviews

Parent Categories