How to set the <img> tag with basic authentication

Viewed 28441

I would like to display the image from a network camera on my web page, but the image is behind a HTTP basic authentication server.

In Firefox and Chrome I can do this:

<img width="320" height="200" src="http://username:password@server/Path" />

But in Internet Explorer 8, I get an empty image box. If I use JQuery to set the src attribute, IE8 displays a blank src. It looks like IE8 is checking the string and rejecting it.

Is there a way to put the basic authentication credentials in the img tag?

6 Answers

Try http proxy.

On server side, enable tinyProxy, create ReversePath to basic authentication server in configuration like:

AddHeader "Authorization" "Basic dXNlcjpwYXNz"
ReversePath "/foo/" "http://somewhere:3480/foo/"

dXNlcjpwYXNz is base64 encoded string from user:pass

Enable reverse proxy in Apache or NGINX to tinyProxy path http://localhot:8888/foo/

Img Source accessable from local server instead of old way deprecated, without http auth pop-up or CORS error.

http://user:pass@somewhere:3480/foo/DEST.jpg

ajax add http header works!

pictureUrl = "https://somewhere/file.jpg";
var oReq = new XMLHttpRequest();
oReq.open("GET", pictureUrl, true);
oReq.setRequestHeader("Authorization", "Basic " + btoa("UserName"+":"+"Password"));
// use multiple setRequestHeader calls to set multiple values
oReq.responseType = "arraybuffer";
oReq.onload = function (oEvent) {
  var arrayBuffer = oReq.response; // Note: not oReq.responseText
  if (arrayBuffer) {
    var u8 = new Uint8Array(arrayBuffer);
    var b64encoded = btoa(String.fromCharCode.apply(null, u8));
    var mimetype="image/jpeg"; // or whatever your image mime type is
    document.getElementById("iOdata").src="data:"+mimetype+";base64,"+b64encoded;
  }
};
oReq.send(null);
Related