Error when generating presigned url from aws s3 using boto3

Viewed 48

When I try to return a generate presigned url using boto3 from bucket in aws s3 and the code:

import fastapi
import boto3
from botocore.exceptions import ClientError

s3 = boto3.client("s3",
                aws_access_key_id="...",
                aws_secret_access_key="...")

BUCKET_NAME = "tayibat-files"

app = FastAPI()                      

@app.get('/{file_name}')
async def method_name(file_name: str):
try:
    url = s3.generate_presigned_url(
                    'get_object',
                    Params={'Bucket': BUCKET_NAME,
                    'Key': f"products/{file_name}"},
                    ExpiresIn=3600
                    )
except ClientError as e:
    logging.error(e)
return url

the get request return an url, but when I try to open it in browsers, It generate:

This XML file does not appear to have any style information associated with it. The document 
tree is shown below.
<Error>
<Code>InvalidRequest</Code>
<Message>The authorization mechanism you have provided is not supported. Please use AWS4-HMAC- 
SHA256.</Message>
<RequestId>ZW269CV1TAYC7CWC</RequestId>
<HostId>1yozjolBbu4difnOjjopLeOk79i34WDOFwp1VQA4Nqd0RBdLNkaOkb/uJVjFtyNu78fx06JfCbI=</HostId>
</Error>
1 Answers

The issue is not your code but your method of authentication or region.

I ran your code sample successfully:

import boto3

session = boto3.session.Session(profile_name="<my-profile>")
client = session.client('s3')

BUCKET_NAME = "<bucket>"
file_name = "<file>"

url = client.generate_presigned_url(
    'get_object',
    Params={'Bucket': BUCKET_NAME,
            'Key': f"products/{file_name}"},
    ExpiresIn=3600
)

print(url)

It worked fine because the region of my bucket aligned with the region of my credentials. When I tried to generate a presigned url from another region I got your same error:

<Error>
<Code>InvalidRequest</Code>
<Message>The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256.</Message>
<RequestId>JJPZYSMZTC7Z8H</RequestId>
<HostId>TsgdZIibKxZ4GVL3h28OJYIvh59yfgeZwVf+eGPXVEzIJsAxdp1VQL67vw20LR/r9uIBxro=</HostId>
</Error>
Related