AWS S3 - Access denied when restricting access to referer

Viewed 411

I have a Next.js app, using the new next/image feature, getting 403-Access denied when attempting to access S3 objects with the following policy:

"Version": "2012-10-17",
"Statement": [
    {
        "Sid": "PublicRead",
        "Effect": "Allow",
        "Principal": "*",
        "Action": [
            "s3:GetObject",
            "s3:GetObjectVersion"
        ],
        "Resource": "arn:aws:s3:::bucket-name/*",
        "Condition": {
            "StringLike": {
                "aws:Referer": [
                    "https://my-website.com/*",
                    "http://localhost:3000/*"
                ]
            }
        }
    }
]
}

The referer is included in the request header as below, as required by S3's docs:

dev tools network tab

If I do remove the Condition from the above policy, it will give access to the image, but that is not what I am looking for.

I have seen related questions in SO and elsewhere by the way, but they do not address this specific issue.

1 Answers

Recently I also started having this problem, starting with in Chrome, then Firefox as well (Edge still working). In search of a solution, I removed the Condition like you state, and it indeed worked.

After checking what could be wrong with the referer condition, it turned out that the format in which the referer is send has changed: instead of the format 'https://example.com/', I see the format 'https://example.com' for my HTTP requests (so without trailing forward slash). The referer send for localhost is 'http://null'.

Changing this in the bucket policy worked for me.

So for you, your condition should look like

        "Condition": {
        "StringLike": {
            "aws:Referer": [
                "https://my-website.com*",
                "http://null"
            ]
        }
    }
Related