0
votes

I am requesting an image from Cloudfront CDN. each time I make a request from the client I am getting this error:

Access to Image at https://cdn.mywebsite/image.png from origin http://localhost:5000 has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin http://localhost:5000 is therefore not allowed access. The response had HTTP status code 403.

I'm using express for the server and have added the following to allow Access but still no luck..

app.use((req, res, next) => {
    res.setHeader('Access-Control-Allow-Origin', "*");
    res.setHeader('Access-Control-Allow-Methods', 'GET');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
    next();
})

Any Advice would be much appreciated!

==========================================================================

Update

Hi @jfriend00

So what my goal is to serve protected content over CF CDN.

For this I am sending signed Cookies to the client using the following module below.

var cf = require('aws-cloudfront-sign')
var options = {keypairId: 'keypairId', privateKeyPath: '/foo/bar'}
var signedCookies = cf.getSignedCookies('https://cdn.mywebsite.com/*', options);

for(var cookieId in signedCookies) {
 res.cookie(cookieId, signedCookies[cookieId]);
}

Then I am simply making a request from the client to the cdn to fetch the image with: <img src="https://cdn.mywebsite.com/image.png" crossorigin="anonymous" alt="test picture">

At this point the Access-Control-Allow-Origin error is displayed in the console.

Note:

var signedUrl = cf.getSignedUrl('https://cdn.mywebsite.com/image.png', options)

This signedUrl works when directly accessing it but not if I make the request from localhost or the website it self.

1

1 Answers

1
votes

CORS headers have to be on the server that is serving the resource. So, if the resource that you are getting the CORS error on is https://cdn.mywebsite/image.png, then that's the host that has to allows CORS access. You can't fix that by allowing CORS on localhost.

FYI, it seems odd that you are getting a CORS error when accessing an image. If you use <img> tag for the access, then the <img> tag will not be subject to same origin restrictions. The same origin restrictions apply to Ajax calls made from browser Javascript.

I also not that you appear to be mixing http and https in the same page which can also cause issues.

Are you trying to download the image with Ajax? Please show your client code that is causing this error and explain what you are trying to accomplish and perhaps we can offer a different solution.