How can I allow only certain file types to be uploaded to my Amazon S3 bucket?

Last updated: 2020-12-08

I want only certain file types to be stored on my Amazon Simple Storage Service (Amazon S3) bucket. How can I limit uploads so that my bucket accepts only those file types?

Resolution

Add statements to your bucket policy that:

  • Allow the s3:PutObject action only for objects that have the extension of the file type that you want
  • Explicitly deny the s3:PutObject action for objects that don't have the extension of the file type that you want
    Note: This explicit deny statement applies the file-type requirement to users with full access to your Amazon S3 resources.

For example, the following bucket policy allows the s3:PutObject action to exampleuser only for objects with .jpg, .png, or .gif file extensions:

Warning: This example bucket policy includes an explicit deny statement. Even the user who enters the bucket policy can be denied access to the bucket if the user doesn't meet the conditions. You must carefully review the bucket policy before you save it. If you get accidentally locked out, see I accidentally denied everyone access to my Amazon S3 bucket. How do I regain access?

{
  "Version": "2012-10-17",
  "Id": "Policy1464968545158",
  "Statement": [
    {
      "Sid": "Stmt1464968483619",
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::111111111111:user/exampleuser"
      },
      "Action": "s3:PutObject",
      "Resource": [
        "arn:aws:s3:::DOC-EXAMPLE-BUCKET/*.jpg",
        "arn:aws:s3:::DOC-EXAMPLE-BUCKET/*.png",
        "arn:aws:s3:::DOC-EXAMPLE-BUCKET/*.gif"
      ]
    },
    {
      "Sid": "Stmt1464968483619",
      "Effect": "Deny",
      "Principal": "*",
      "Action": "s3:PutObject",
      "NotResource": [
        "arn:aws:s3:::DOC-EXAMPLE-BUCKET/*.jpg",
        "arn:aws:s3:::DOC-EXAMPLE-BUCKET/*.png",
        "arn:aws:s3:::DOC-EXAMPLE-BUCKET/*.gif"
      ]
    }
  ]
}

Note: For the first Principal value, list the Amazon Resource Names (ARNs) of the users that you want to grant upload permissions to. For the Resource and NotResource values, be sure to replace DOC-EXAMPLE-BUCKET with the name of your bucket.


Did this article help?


Do you need billing or technical support?