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?
Here's how to use it: const imageId = 'some-image'; const imageUrl = 'https://api.example.com/secret-image.png'; const authToken = 'changeme'; displayProtectedImage(imageId, imageUrl, authToken); Yay!
To send a request with the Bearer Token authorization header, you need to make an HTTP request and provide your Bearer Token with the "Authorization: Bearer {token}" header. A Bearer Token is a cryptic string typically generated by the server in response to a login request.
JSON Web Token (JWT, RFC 7519) is a way to encode claims in a JSON document that is then signed. JWTs can be used as OAuth 2.0 Bearer Tokens to encode all relevant parts of an access token into the access token itself instead of having to store them in a database.
To send a POST JSON request with a Bearer Token authorization header, you need to make an HTTP POST request, provide your Bearer Token with an Authorization: Bearer {token} HTTP header and give the JSON data in the body of the POST message.
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://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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With