What do I set CORS settings to and where so that m

2019-01-20 15:49发布

问题:

I have a big canvas with icons and pictures that all come from my S3 bucket. When I'm trying to upload it (which runs toDataUrl) Chrome complains that

Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.

I've encountered this error before, but my solution that time was to host all the images locally. This is not possible this time, however, so I will need to tackle this issue head on.

Googling this issue brings up a lot of stuff about CORS, which I don't understand.

I've tried the following settings in my S3 bucket:

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

This, however, does not work.

My intuition tells me I have to change something in the server as well, otherwise what is the purpose of this security requirement?

So what do I change, and where, so that my canvas won't be tainted anymore?

回答1:

Your CORS configuration should be good, the minimal needed being

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

What you need however, is to set your <img>'s crossOrigin attribute to "anonymous".

Also, check that the image on s3 has been made Public (there should be a grantee Everyone set to Open/Download), and that you use the link available in the Properties tab of your image file (something like https://s3.yourRegion.amazonaws.com/userName/Folder/file.png).

And finally, you have to clear the browser's cache after you changed your bucket's CORS setting, otherwise the browser won't make a new request to the server and it will use the unsafe version it has cached.