tsayen / dom-to-image

Generates an image from a DOM node using HTML5 canvas
Other
10.28k stars 1.68k forks source link

CORS authentication not enabled #255

Open TheBillLang opened 5 years ago

TheBillLang commented 5 years ago

Use case: description, code

Print with easyprint a react leaflet map from a server requiring authentication

Expected behavior

Pass authentication token to map server

Actual behavior (stack traces, console logs etc)

CORS request refused

Code change required

Add: request.withCredentials = true; at line 476

Browsers

iqdoq-dfischer commented 5 years ago

Authentication credentials may also be required in function makeImage.

Additionally we had to add ... image.crossOrigin = 'use-credentials'; ... in that makeImage function.

See "MDN: Allowing cross-origin use of images and canvas" .

Sending (existing) credentials for authentication of external URI (CORS) requests should be configurable.

Requirement: The remote webserver hosting the images/resources has to respond with appropriate CORS headers to let the browser know that the cross domain request from that origin is safe/allowed.

I will provide a patch on my own fork if I find time...

TheBillLang commented 5 years ago

Excellent change. It turns my hack into real code. Thanks.

Alas, my situation became more complex. When only some resource servers require authentication 'use-credentials' must be not only configurable but also conditional. I my case the map server requires authentication but the photo server does not. The server urls are distinct, so I ended up enclosing 'use-credentials' with

if (url.search(new RegExp("api", "i")) > 0)

A generic solution for that situation will be much more difficult.

MSCAU commented 3 years ago

image.crossOrigin = 'use-credentials';

@iqdoq-dfischer - I have added the line that you have proposed:

        function makeImage(uri) {
            return new Promise(function (resolve, reject) {
                var image = new Image();
                image.crossOrigin = 'Anonymous';
                image.onload = function () {
                    resolve(image);
                };
                image.onerror = reject;
                image.src = uri;
            });
        }

I obviously don't have access to the maps.stamen.com server and I still get the CORS error when trying to save a Leaflet map using dom-to-image. Oddly don't have this issue at all in Firefox which suggests it's a (recent) Chrome limitation. Do you have any suggestions?

See also https://github.com/stamen/maps.stamen.com/issues/158

danhyltoftlund commented 2 years ago

What is the chance of getting request.withCredentials = true; added or a possibility turn it on or off.

If I do a fork, implement the change and create a PR. Is there any chance it would be approved and added to the release?