Basic idea
Load the images via JavaScript and display them on the site. The advantage is that the authentication credentials will never find their way into the HTML. They will resist at the JavaScript side.
Step 1: load the image data via JS
That’s basic AJAX functionality (see also XMLHttpRequest::open(method, uri, async, user, pw)
):
var xhr = new XMLHttpRequest();
xhr.open("GET", "your-server-path-to-image", true, "username", "password");
xhr.onload = function(evt) {
if (this.status == 200) {
// ...
}
};
Step 2: format the data
Now, how can we display the image data? When using HTML, one would normally assign an URI to the src
attribute of the image element. We can apply the same principle here except for the fact that we use data URIs instead of ‘normal’ http(s)://
derivates.
xhr.onload = function(evt) {
if (this.status == 200) {
var b64 = utf8_to_b64(this.responseText);
var dataUri = 'data:image/png;base64,' + b64; // Assuming a PNG image
myImgElement.src = dataUri;
}
};
// From MDN:
// https://developer.mozilla.org/en-US/docs/Web/API/window.btoa
function utf8_to_b64( str ) {
return window.btoa(unescape(encodeURIComponent( str )));
}
Canvas
There is also another option which consists in painting the loaded data in a <canvas>
field. This way, the user won’t be able to right-click the image (the area where the canvas is positioned) as opposed to the <img>
and data URIs where the user will see a long data URI when viewing the image properties panel.