使用Bearer令牌在JavaScript中加载图像 [英] Loading Image in JavaScript with Bearer token

查看:121
本文介绍了使用Bearer令牌在JavaScript中加载图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在这样在JS中加载图像:

I am loading an image in JS like this:

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

这会有效,但我已经意识到我必须使用OAuth 2在服务器端保护我的图像(与应用程序的其余部分一样)这对我来说只会收到401 Unauthorized。

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.

这是一个 angular 应用程序和我确实有一个拦截器为所有对服务器的角度服务请求添加了Authorization头,但在这种情况下 - 当然没有使用拦截器,因为调用不是在角度上下文中进行的。

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.

有关如何将授权标头添加到获取请求的任何想法?

推荐答案

如果服务器端的可能性有限,也可以调用 GET XMLHttpRequest 使用相应的 access_token 请求并使用 src ://tools.ietf.org/html/rfc2397\"rel =noreferrer>数据URI方案使用 base64 编码的响应构建如下:

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

这篇关于使用Bearer令牌在JavaScript中加载图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆