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

Duplicate values of React object properties when using .push method within a loop

In my code, I've implemented a function called handleCreate that is responsible for taking user data and inserting it into a database. Within the loop of aliasArr.forEach(), I am sending new user instances to my database for each element in the alias ...

Tips for iterating through data in JSON format and displaying it in a Codeigniter 4 view using foreach

As a newcomer to JSON, I have a question - how can I iterate through JSON data (which includes object data and object array data) using jQuery/javascript that is retrieved from an AJAX response? To illustrate, here is an example of the JSON data: { "p ...

Unable to locate $element post minification

I've encountered a peculiar bug that only seems to manifest when my web application is running in Karaf, but not on the webpack-dev-server. Whenever I open a dialog while the web app is running in Karaf, I receive this error in the browser console: a ...

Injecting CSS styles into a webpage using a Chrome extension before the page has completely loaded to achieve instant customization

As a newcomer to creating Chrome (or other browser) extensions, I am working on developing one that applies custom CSS rules to specific page elements. Overall, it seems to be functioning as intended, but with some minor issues. One issue I have encounter ...

Why does my console refuse to log the input entered for the search?

Looking to become proficient in web development, I am attempting to record HTML search queries in the console after storing them in a variable. However, when I try running the search procedure, nothing seems to be displaying in my browser's inspect co ...

What could be causing JavaScript fetch to only send OPTIONS requests instead of the expected calls?

I'm having an issue with my AJAX request using javascript fetch. It's only sending an OPTIONS call and not proceeding to make further calls. What's strange is that the response header seems fine, and $.ajax is working as expected. Check out ...

Sending the image's identification number as a parameter to a function and showing the total number

On a static page, I have the following HTML markup: <div class="middle-content"> <div class="white-div"> <div class="like-buttons"> <img id="1" src="up.png" onclick="onClick(true, this.id)" /> &l ...

What is causing the error to occur during the installation of the NestJS Client?

Encountered an error while attempting to install the nestjs client, and I'm completely puzzled by this issue. PS C:\Users\meuser> npm i -g @nestjs/cli npm ERR! code ETARGET npm ERR! notarget No matching version found for @angular- ...

I am uncertain about whether it would be better to utilize URL path parameters or query parameters for filtering on the back-end of the application

Suppose I am trying to retrieve all car models from a specific brand. This can be achieved by utilizing URL path parameters or query parameters as shown below: router.get('/modelsByBrand', modelController.getModelsByBrand); To make the GET reque ...

Detach an item from its parent once it has been added to an array

Currently, I am facing an issue with a form on my blog. The blog is represented as an object that contains multiple content objects within it. I seem to be experiencing some confusion because the reactivity of the content I add to the Array persists with t ...

Incorporate React into current Node express application by utilizing a content delivery network (CD

I'm currently in the process of developing a web application utilizing both Node and React. Instead of having separate Node and React applications, I decided to integrate React directly into my existing setup. To achieve this, I attempted importing th ...

Implementing the ui-tinymce Directive Within a Different Directive

I am attempting to implement the ui-tinymce directive within another directive: angular.module("risevision.widget.common.font-setting", ["ui.tinymce"]) .directive("fontSetting", ["$templateCache", function ($templateCache) { return { restrict: ...

Error message: App not defined in Ember App.router

Attempting to set up routing for my app for the first time, but struggling to grasp the logic. I managed to render my templates by adding the following code to my route.js file: import Ember from 'ember'; import config from './config/enviro ...

Is there a way to maintain the second form's state when the page is refreshed using Vue.js?

I have a challenge in creating a web-app with only 2 pages. The first page requires filling out forms across two stages, but I am unable to create separate pages for this purpose. Is there a way to display two forms on one page and remain on the second for ...

Property that is dynamically populated based on data retrieved from an external API

My template relies on an API call (Firebase) to determine the return value of my computed property, which in turn decides whether certain elements are displayed. However, I've noticed that my computed property is not reactive - its value in the templ ...

Checking for a particular element's existence in an array using jQuery

Is there a way to verify the presence of the var element in the array sites? var sites = array['test','about','try']; var element = 'other'; ...

Utilize existing *.resx translation files within a hybrid application combining AngularJS and Angular 5

Greetings! I currently have an AngularJS application that utilizes $translateProvider for internalization and WebResources.resx files: angular.module('app') .config(['$translateProvider', 'sysSettings', 'ngDialogProv ...

Implementing a feature to insert a horizontal rule button in React Draft Wysiwyg

I am currently working on implementing a custom button in React Draft Wysiwyg that will allow me to add an <hr> tag to my content. Although I have followed the demos and documentation, I have encountered an issue where the custom button successfully ...

PreventDefault doesn't work well with Bootstrap toggling data

When working with a list of elements, each containing an ng-click, I encountered an issue. Nested inside each element is a div that is meant to toggle a Bootstrap modal. To prevent the ng-click event from the parent element from firing, I added $event.sto ...

Steps to eliminate pre-chosen alternatives upon loading select control?

When using react-select with pre-selected options and multiple select enabled, the issue arises where clicking on the Select box still displays the already pre-selected options. How can I remove these duplicate options from the list? Below is a snippet of ...