Loading Image in JavaScript with Bearer token

安稳与你 提交于 2019-11-30 17:51:26

问题


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?


回答1:


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();



回答2:


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://tools.ietf.org/html/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.



来源:https://stackoverflow.com/questions/35079576/loading-image-in-javascript-with-bearer-token

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!