title: Getting S3 CORS Access-Control-Allow-Origin to dynamically echo requesting domain
body: <p>How can I set the S3 CORS <code>AllowedOrigin</code> configuration such that it dynamically echos the requesting domain in the <code>Access-Control-Allow-Origin</code> header?</p>
  
  <p>In the post, <a href="http://virtuallyhyper.com/2013/08/cors-with-cloudfront-s3-and-multiple-domains/" rel="noreferrer">"CORS with CloudFront, S3, and Multiple Domains"</a>, it is suggested that setting <code>AllowedOrigin</code> to <code>&lt;AllowedOrigin&gt;*&lt;/AllowedOrigin&gt;</code> does this. However, S3 returns <code>Access-Control-Allow-Origin: *</code> instead.</p>
  
  <p><code>Access-Control-Allow-Origin: *</code> does not work in my case as I am using <code>image.crossOrigin = "use-credentials"</code> in a JavaScript app. With this option, S3 returns <code>Access-Control-Allow-Credentials: true</code>. Cross origin access to the image then fails because <a href="https://stackoverflow.com/questions/19743396/cors-cannot-use-wildcard-in-access-control-allow-origin-when-credentials-flag-i">using wildcard as the allowed origin in conjunction with credentials is not permitted</a>.</p>
  
  <p>Background for why this is needed:</p>
  
  <p>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.</p>
  
  <p>For the authentication to work, <code>image.crossOrigin = "use-credentials"</code> 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 <code>crossOrigin</code> is set to <code>anonymous</code>, credentials are still sent. But not on Safari 7.0.4. Consistent cross-browser behavior could only be obtained using <code>use-credentials</code>.).</p>
  
  <p>Because browsers transparently redirects to the S3 URL, credentials are also sent.</p>