Loading Image in JavaScript with Bearer token

帅比萌擦擦* 提交于 2019-11-30 22:00:35

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

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.

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