Anand
Anand

Reputation: 195

Why i am getting an error when fetching from S3 Bucket url?

I tried uploading the image on s3 bucket, image is uploaded successfully but when I fetch the URL, it says "Access Denied".

*PS : I have unchecked Restrict public access enter image description here

Upvotes: 0

Views: 1949

Answers (2)

Robinson De La Cruz
Robinson De La Cruz

Reputation: 156

You can use a presigned url. All objects by default are private. Only the object owner has permission to access these objects. However, the object owner can optionally share objects with others by creating a presigned URL, using their own security credentials, to grant time-limited permission to download the objects [1].

You need to create an user with programatic access with the permissions necessary [2].

const S3 = require('aws-sdk/clients/s3');

function async getObject(objectKey) {
  const s3 = new S3({
    accessKeyId: userAwsAccessKey,
    secretAccessKey: userAwsSecretAccessKey,
  });
  
  try {
    // S3 library documentation [3]
    const url = await s3.getSignedUrlPromise('getObject', {
      Bucket: bucketName,
      Key: objectKey,
      Expires: 60, // seconds
    });

    return url;
  } catch (error) {
    throw new Error(error);
  }
}

[1] https://docs.aws.amazon.com/AmazonS3/latest/userguide/ShareObjectPreSignedURL.html

[2] https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users_create.html#id_users_create_api

[3] https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#getSignedUrlPromise-property

Upvotes: 0

Anand
Anand

Reputation: 195

Adding this to Bucket Policy solved the problem !!!

{
  "Version":"2012-10-17",
  "Statement":[
    {
      "Sid":"PublicRead",
      "Effect":"Allow",
      "Principal": "*",
      "Action":["s3:GetObject","s3:GetObjectVersion"],
      "Resource":["arn:aws:s3:::Bucket_Name/*"]
    }
  ]
}

Upvotes: 2

Related Questions