Search code examples
node.jsaws-sdkaws-sdk-js

Returned URL from getSignedUrl not working


I've been implementing aws s3 for the first time using aws-sdk on Node.js

I'm currently attempting to getSignedUrl and PUT to it from the client. However, when I attempt to PUT it will return a 403 status code.

This is my back-end code:

const s3 = new AWS.S3({
  accessKeyId: keys.accessKeyId,
  secretAccessKey: keys.secretAccessKey
});

app.get('/api/upload', requireLogin, (req, res) => {
  let key = `${req.user.id}/${uuid()}.jpeg`
  s3.getSignedUrl('putObject', {
    Bucket: 'advanced-node-blog',
    ContentType: 'image/jpeg',
    Key: key
  },
  (err, url) => res.send({ key, url }));
});

On the front-end:

// presigned URL
const uploadConfig = await axios.get('/api/upload');

await axios.put(uploadConfig.data.url, file, {
  headers: {
    'Content-Type': file.type
  }
});

When I GET to the URL, I will receive this message:

The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256.

I researched on this error and came to the conclusion I was missing signatureVersion: 'v4',. When I added this, however, the error changed to Error parsing the X-Amz-Credential parameter; the region 'us-east-1' is wrong; expecting 'us-east-2'

SO I then added region: 'us-east-2'. The error then changed to The request signature we calculated does not match the signature you provided. Check your key and signing method.

I changed created new credentials and set them but still not progress..

Any clues as to what I might be doing wrong?

Thank you in advance!


Solution

  • The problem was a preflight failure involving the old CORS configuration of my bucket. It was fixed by adding the following configuration:

    <CORSRule>
      <AllowedOrigin>*</AllowedOrigin>
      <AllowedMethod>GET</AllowedMethod>
    </CORSRule>
    <CORSRule>
      <AllowedOrigin>*</AllowedOrigin>
      <AllowedMethod>PUT</AllowedMethod>
    </CORSRule>