9

I am loading an image in JS like this:

var img = new Image();
img.onload = function () {
..
};
img.src = src;

This will work, but I have realized that I must secure my images on the server side with OAuth 2 (as with the rest of the application) and this will effect in me simply receiving a 401 Unauthorized.

This is an angular app and I do have an interceptor adding the Authorization header consequently for all the angular service requests to the server, but in this case of course - the interceptor is not used because the call is not made in an angular context.

Any ideas to how I can add the Authorization header to the get request?

Marcus
  • 8,230
  • 11
  • 61
  • 88
  • How is the application being served? node.js? IIS? – mindparse Jan 29 '16 at 08:20
  • By .NET WebApi 2. The image is returned by a method implemented as a REST GET controller method and this will be deployed in Azure, so yeah.. IIS. – Marcus Jan 29 '16 at 08:37
  • May be http://stackoverflow.com/questions/20997406/force-http-interceptor-in-dynamic-ngsrc-request will get you on right path. – Prashant Jan 29 '16 at 09:10
  • Thank you @PrashantPalikhe but unfortunately in this situation it will not help me. I am trying to *programmatically* load img into variable, I do not even have an img element (I could create that to programmatically though, but I don´t think that is the way to go). – Marcus Jan 29 '16 at 09:15

2 Answers2

10

In case you have limited possibilies at server side it is also possible to invoke a GET XMLHttpRequest request with the appropriate access_token and set the image src with a data URI scheme build from the response encoded with base64 as follow :

var request = new XMLHttpRequest();
request.open('GET','https://dl.content.com/contentfile.jpg', true);
request.setRequestHeader('Authorization', 'Bearer ' + oauthToken.access_token);
request.responseType = 'arraybuffer';
request.onload = function(e) {
    var data = new Uint8Array(this.response);
    var raw = String.fromCharCode.apply(null, data);
    var base64 = btoa(raw);
    var src = "data:image;base64," + base64;

    document.getElementById("image").src = src;
};

request.send();
Community
  • 1
  • 1
manuc66
  • 2,701
  • 29
  • 28
8

Just add the bearer token to the URL:

var img = new Image();
img.onload = function () {
..
};
img.src = src + '?access_token=mF_9.B5f-4.1JqM';

That, at least is how the OAuth 2 spec reads: https://www.rfc-editor.org/rfc/rfc6750#section-2.3

And although this methodology has a number of drawbacks, the authors forsaw issues with things of this nature, which is why it is there.

Community
  • 1
  • 1
John Green
  • 13,241
  • 3
  • 29
  • 51