Displaying Photo on Webpage using Bearer Authorization Token in JavaScript

In my JavaScript code, I am currently loading an image using the following method:

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

However, I have recently realized that I need to secure the images on my server side with OAuth 2, just like the rest of my application. This means that I will receive a 401 Unauthorized error when trying to load the images.

My application is built using Angular and I have an interceptor set up to add the Authorization header to all service requests made through Angular. But in this case, since the image call is not made within an Angular context, the interceptor is not applied.

Does anyone have any suggestions for how I can add the Authorization header to the get request for the image?

Answer №1

If your server side options are limited, you can also trigger a GET request using XMLHttpRequest with the appropriate access_token and utilize the image src attribute to display the content by encoding the response in base64 and creating a data URI scheme as shown below:

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

Answer №2

To include the bearer token in the URL, simply follow these steps:

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

This approach aligns with the OAuth 2 specification: https://www.rfc-editor.org/rfc/rfc6750#section-2.3

While this method has its limitations, the creators anticipated potential issues and incorporated it as a solution.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

ng-if not functioning properly in Internet Explorer 8

Currently, I am developing a substantial Angular application that needs to be compatible with IE8. However, we are encountering performance problems as we implement ng-show extensively on the homepage. I am considering using ng-if to completely remove pa ...

Can whitelist functionality be applied in the browser version of Babel?

While working on a project for my university, I wanted to utilize React. Since installation wasn't allowed, I had to resort to using the browser version of React. Everything was functioning well until I attempted to incorporate JSX into the browser. ...

Extract the Date portion from a DateTime object in ASP.NET MVC

I am currently facing an issue with a property in my Model [Display(Name = "День рождения")] [DataType(DataType.Date)] public System.DateTime Birthday { get; set; } When trying to save the value to the database using AJAX, it is also ...

Middleware for enabling the Cross-Origin Resource Sharing (CORS) functionality to efficiently manage preflight

My CORS configuration is set up globally to handle credentials like this: app.use(cors({ origin: 'https://example.com', credentials: true })) However, there are certain routes where I need to allow OPTIONS requests. Following the documentation, ...

Top method for identifying browser window modifications such as navigating back, altering the URL, refreshing, or closing the window

Currently, I am developing a testing application that requires me to trigger a finsihTheTest() function in specific situations. These situations include: When the user attempts to reload the page. When the user tries to navigate back from the page. If the ...

I'm feeling confused about the breaking change in Angular 1.4.0 and its select feature

Today, a new version of angular (1.4.0) has just been released. According to the changelog, there is a notable change regarding "selects". In the past, I used selects in this manner: controller snippet: // Setting default selection $scope.filters = { ...

Tips for correctly updating the status of a checkbox linked to a database

I need some guidance on handling the state change of an input checkbox in React. The checkbox's initial value is determined by a boolean retrieved from a database. Currently, I am using defaultChecked to set the checkbox initially based on this boolea ...

Struggling with AngularJS routing woes

I've been struggling to get my JavaScript code working. As a JavaScript newbie, I was trying to implement a routing example in AngularJS that I found online. Despite spending numerous hours on it, I couldn't get it to work. Problem: The default ...

Passing PHP value from a current page to a popup page externally: A guide

I'm currently facing an issue at work where there is a repetitive button and value based on the database. I need to extract the selected value from the current page into a pop-up page whenever the corresponding button is clicked throughout the repetit ...

Tips for preventing the occurrence of undefined when retrieving data?

After fetching data from mongo, I encountered an issue where my useState([]) is initially defined as undefined. Can someone please offer a solution to this problem? const router = useRouter() const {id} = router.query console.log(id) // f ...

Enhance and Modify feature using Javascript

I'm facing two issues with my product information form. Firstly, after I submit the data, I want the input fields to be cleared automatically. Secondly, the edit function doesn't seem to work at all. I'm quite stuck on how to resolve these p ...

How to break out of an endless loop in Node.js and Express.Js

I have developed an Express app that is designed to paginate through an external API call. I have thoroughly examined the code but for some reason, the loop condition to break the function isn't being triggered. Any assistance on this matter would be ...

The Angular watcher is not triggered when listening for changes from the Date() function

Can someone please help me with a question I have about an Angular directive I am working on? I am new to Angular and it took a lot of courage to ask this question here ;) The directive I have displays the time in a specific format: Application.Directives ...

unable to add browse-sync to Ubuntu 16.04

I recently installed nodejs and npm and attempted to install browser-sync using the command npm install -g browser-sync. However, I encountered an error. npm install -g browser-sync npm ERR! Linux 4.15.0-101-generic npm ERR! argv "/usr/bin/nodejs" "/ ...

Track and manage date ranges inclusive of specific times

http://jsfiddle.net/7vzapm49/1/ var startdatearr = [new Date("04 Dec 2014 14:30:00").toUTCString(), new Date("07 Dec 2014 14:30:00").toUTCString()]; var enddatearr = [new Date("05 Dec 2014 14:30:00").toUTCString(), new Date("08 Dec 2014 14:30:00").toUTCSt ...

Pedaling back and forth along a sequence

Is there a way to implement forward and backward buttons for a clickable list without using arrays, as the list will be expanding over time? I have already achieved changing color of the listed items to red, but need a solution to navigate through the list ...

What is the purpose of using $ symbols within NodeJS?

Lately, I've been attempting to grasp the ins and outs of using/installing NodeJS. Unfortunately, I'm feeling a bit lost due to tutorials like the one found here and their utilization of the mysterious $ symbol. Take for instance where it suggest ...

What is the method for altering the date format of a published article?

I am looking to modify the date format of a published post in WordPress. Currently, the date format is <?php the_time('m.d.y'); ?></div>, which appears as "1.20.2018". My goal is to change it to "January 20, 2018". Can anyone guide ...

Issue with Hover Effect on Safari Browser

Encountering a peculiar issue exclusively in Safari - when hovering over a link in the header, the links to the right of the hovered-over link alter their size (appearing smaller) during the hover animation. Once the animation concludes, these links revert ...

Ways to merge multiple cells horizontally in a table right from the beginning

Is there a way to start the colspan from the second column (Name)? See image below for reference: https://i.stack.imgur.com/RvX92.png <table width="100%"> <thead style="background-color: lightgray;"> <tr> <td style="width ...