Getting S3 CORS Access-Control-Allow-Origin to dyn

2019-01-22 00:08发布

问题:

How can I set the S3 CORS AllowedOrigin configuration such that it dynamically echos the requesting domain in the Access-Control-Allow-Origin header?

In the post, "CORS with CloudFront, S3, and Multiple Domains", it is suggested that setting AllowedOrigin to <AllowedOrigin>*</AllowedOrigin> does this. However, S3 returns Access-Control-Allow-Origin: * instead.

Access-Control-Allow-Origin: * does not work in my case as I am using image.crossOrigin = "use-credentials" in a JavaScript app. With this option, S3 returns Access-Control-Allow-Credentials: true. Cross origin access to the image then fails because using wildcard as the allowed origin in conjunction with credentials is not permitted.

Background for why this is needed:

In my setup, access to images on S3 has to go through our domain, where authentication is required to restrict access and check if an account is authorized to access the images. If it is, the server returns a 302 redirect to an S3 URL.

For the authentication to work, image.crossOrigin = "use-credentials" has to be set so that the request hits my server with the required credentials. (Incidentally, when I tested on Firefox 30.0 and Chrome 35.0.1916.153, if crossOrigin is set to anonymous, credentials are still sent. But not on Safari 7.0.4. Consistent cross-browser behavior could only be obtained using use-credentials.).

Because browsers transparently redirects to the S3 URL, credentials are also sent.

回答1:

AWS's CORS documentation does not document this, but I managed to get the answer in a thread on AWS Developer Forums, where I found that AWS changed the original behavior of echoing the requesting domain if * is being used for AllowedOrigin.

To get S3 to dynamically echo the requesting domain, AllowedOrigin has to be set as such:

<AllowedOrigin>http://*</AllowedOrigin>
<AllowedOrigin>https://*</AllowedOrigin>


回答2:

For me it seemed to be some kind of caching issue (even though I was not using cloudfront, only S3). Appending a random parameter to the URL fixed the issue for me, e.g.

https://s3-amazon.com/bucket/file.jpg?d=3243253456346

I also had the following CORS settings in S3:

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
    <CORSRule>
        <AllowedOrigin>http://*</AllowedOrigin>
        <AllowedOrigin>https://*</AllowedOrigin>
        <AllowedMethod>GET</AllowedMethod>
        <MaxAgeSeconds>3000</MaxAgeSeconds>
        <AllowedHeader>*</AllowedHeader>
    </CORSRule>
</CORSConfiguration>