- Newest
- Most votes
- Most comments
Hi Rafa,
The simplest way to achieve your desired solution would be to obtain new credentials by assuming a role using STS for every pre-signed URL you want to create, and with those assumed credentials create the pre-signed URL. That way you have total control over the session expiry time. It's pretty much the same code you already have, but instead of checking the expiry time, just create temporary credentials for every pre-signed URL. For reference the assume_role doc is here https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sts/client/assume_role.html#
Thank you Pablo for your reply. I have verified your solution works. For the temporary credentials I created a new IAM role different from the one assigned to the instance profile. Permissions for GetObject and PutObject granted through bucket policy to the new role as principal.
The following "toy" script (no error checking, hardcoded values) illustrates the sequence of calls.
import boto3 # role info role_to_assume = 'MyRole' account_id = "123456789012" role_duration = 7200 # file and preshared URL info bucket = "foo-1234" path = "bar" file_name = "file6.txt" object_key = path + "/" + file_name region = 'eu-west-1' url_expire = 3600 # Create an STS client sts_client = boto3.client('sts') # Assume role assumed_role_object=sts_client.assume_role( RoleArn="arn:aws:iam::" + account_id + ":role/"+role_to_assume, RoleSessionName="RoleForPresharedURL", DurationSeconds = role_duration ) temp_credentials = assumed_role_object['Credentials'] # S3 client with temp credentials from role s3_client = boto3.client( 's3', aws_access_key_id=temp_credentials['AccessKeyId'], aws_secret_access_key=temp_credentials['SecretAccessKey'], aws_session_token=temp_credentials['SessionToken'], region_name=region ) # upload file to bucket s3_client.upload_file(file_name, bucket, object_key) # presigned URL presigned_url = s3_client.generate_presigned_url( 'get_object', Params = {'Bucket': bucket, 'Key': object_key}, ExpiresIn = url_expire ) print(presigned_url)
Relevant content
- Accepted Answerasked 7 months ago
- Accepted Answerasked 9 months ago
- Accepted Answerasked 6 months ago
- AWS OFFICIALUpdated a year ago
- AWS OFFICIALUpdated 10 months ago
- AWS OFFICIALUpdated 2 years ago