Kasichainula Keshav
Kasichainula Keshav

Reputation: 35

Access other aws user s3 buckets using boto3

I am making an Django web application that can list users s3 buckets and also let me access the other users files in s3 bucket. Is there any way that I can access other users accounts like some temporary credentials using boto3?

Upvotes: 2

Views: 9792

Answers (1)

maafk
maafk

Reputation: 6876

boto3 has the assume_role method which returns temporary credentials for the role.

In order for this to work, the account you're accessing must have a role with policies allowing access to the S3 bucket, and the role itself must have a trust relationship with the account you're calling from.

Also the instance that's running your django application should have an instance role that allows AssumeRole permission.

Code would look something like

import boto3

sts = boto3.client('sts')
response = sts.assume_role(
    RoleArn='aws:arn:iam::OTHERACCOUNTID:role/role-that-allows-s3-access',
    RoleSessionName='my-random-session-name',
    DurationSeconds=900 # how many seconds these credentials will work
)

s3 = boto3.client(
    's3',
    aws_access_key_id=response['Credentials']['AccessKeyId'],
    aws_secret_access_key=response['Credentials']['SecretAccessKey'],
    aws_session_token=response['Credentials']['SessionToken']
)

response = s3.list_objects(
    Bucket='bucket-in-other-account'
)

Upvotes: 12

Related Questions