Visual Verification

I'm currently working on a NestJS application that serves images with authentication requirements. I have implemented JWT for authentication, but I encountered an issue when trying to display the image in an img tag because I cannot attach the Authorization header to the GET request. I've come across some articles suggesting the use of Signed URLs for file authentication, but I haven't found clear instructions on how to implement it.

My backend API is built using NestJS and I am using MINIO as my datastore.

Answer №1

When it comes to serving authenticated images within your NestJS application, a useful approach is to leverage Signed URLs with Minio. These Signed URLs grant temporary access to resources without requiring an Authorization header, making them ideal for situations where you need to serve images in <img> tags.

// Setting up an Image controller to handle signed URLs
@Controller('images')
export class ImageController {
  constructor(private imageService: ImageService) {}

  @Get(':filename')
  @UseGuards(AuthGuard()) // Route protection with authentication
  async getImage(@Param('filename') filename: string, @Req() req: Request) {
    try {
      const signedUrl = await this.imageService.generateSignedUrl(filename, req.user);
      return { signedUrl };
    } catch (error) {
      // Error handling
    }
  }
}

// Service responsible for generating signed URLs for images
@Injectable()
export class ImageService {
  constructor(private minioClient: MinioClient) {}

  async generateSignedUrl(filename: string, user: any): Promise<string> {
    // Logic for creating a signed URL for the image based on the filename and user
    // Utilize the Minio SDK to generate the signed URL
    // Example:
    // const signedUrl = await this.minioClient.presignedGetObject('bucketName', filename);
    return signedUrl;
  }
}

Example of implementation:

<img src="signedUrlFromBackend" alt="Image" />

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

User creation causing redirection malfunction

Recently, while working on a website, I encountered an issue with the registration process for users. It was functioning properly when I tested it a few days ago. After making some updates to other aspects of the website such as the login and profile sect ...

Dependency injection in Angular 2 service not functioning as expected

I am facing an issue while trying to retrieve static data from UserService in Angular 2. Although everything seems correct based on the documentation, it is not functioning as expected. Below is my UserComponent.ts import {Component ,OnInit } from ' ...

Why am I unable to insert data into the 'sessions' database using connect-mongo?

I am utilizing connect-mongo in conjunction with express-session, and the session data is successfully being stored in Mongo. However, I want to enhance the sessions collection utilized by connect-mongo in order to include my own fields on top of it. I h ...

Having Trouble Assigning Three JS Material to Mesh Object

This is the code snippet for creating a glass material: const glassMaterial = new THREE.MeshPhysicalMaterial( { // color: 0xffffff, metalness: 0.25, roughness: 0, transmission: 1.0 color: 0xffffff, metalness: 0.25, roughness: 0, transmi ...

Having trouble sending ajax requests in Node.js?

I am currently utilizing a nodejs server for my website, and I am looking to have the backend server initiate a call to an api on an external server. My initial attempt at achieving this was through the following simple and direct method: router.post(&apo ...

Deleting a model using RestAPI and referencing another model

UPDATE: My professor just advised me to access the driver only from within the admin, not from the admin. Currently, I am developing a project that involves using restAPI's, and one of the requirements is that an admin should be able to delete a driv ...

Modifying Label text dynamically using jQuery on Click event

My website HTML contains the following code snippet: <script src="js/jquery.flexslider.js"></script> <script src="js/jquery.rings.js"></script> The contents of jquery.rings.js are as follows: $('input[type="image"]') ...

Error message in Typescript: When a class has initialized properties, a 'super' call must be the first statement in the constructor

I am currently facing some typescript errors in my project. Would you like to see a sample of the code that is causing the issue? Here is a snippet: module CoreWeb { export class Controller implements IController { public $q; ... This piece of cod ...

Is it possible to iterate over a non-reactive array in a Vue template without having to store it in a data property or computed property?

Presented below is a static array data: const colors = ["Red", "Blue", "Green"]; To display these values in my markup, I can use the following method in React: import React from "react"; // Static array of colors const colors = ["Red", "Blue", "Green"] ...

What is the significance of the "component" prop within MUI components?

I am a beginner in React and HTML. Currently, I am using MUI and React to create my own website. I am currently attempting to add an "Upload button" that will allow me to select an image file when clicked. Below is the official implementation: <Button ...

Tips for styling the Button component in the shadcn/ui library for maximum impact

I'm currently working on a project using the shadcn/ui library. How can I properly customize it to meet my specific needs? For example, let's say I require an extra large red rounded Button for a call-to-action button in my project. What would be ...

Implementing background color changes based on a database value (sex) using JavaScript

Visualization: [IMG]+[HIDDEN INPUT]-—-[TEXT]-—-[ICON] [IMG]+[HIDDEN INPUT]-—-[TEXT]-—-[ICON] [IMG]+[HIDDEN INPUT]-—-[TEXT]-—-[ICON] (For each individual) I am looking to match the background color of the icon on the right with the IMG on the ...

What is the process for retrieving the value of `submit.preloader_id = "div#some-id";` within the `beforesend` function of an ajax call?

In my JavaScript code, I have the following written: var formSubmit = { preloaderId: "", send:function (formId) { var url = $(formId).attr("action"); $.ajax({ type: "POST", url: url, data: $(formId).serialize(), dataTy ...

Is it considered poor practice in TypeScript to manually set the type when the type inference is already accurate?

Is it necessary to explicitly set the variable type in TypeScript when it is inferred correctly? For example: const add = (a: number, b: number) => a + b; const result = add(2, 3); // Or should I explicitly declare the return value type? const add = ...

There was an error encountered: Uncaught TypeError - Unable to access the 'append' property of null in a Typescript script

I encountered the following error: Uncaught TypeError: Cannot read property 'append' of null in typescript export class UserForm { constructor(public parent: Element) {} template(): string { return ` <div> < ...

Attempting to implement an EventListener to alter the navbar upon scrolling, unsuccessful at the moment

Exploring ways to update the navigation bar upon scrolling to shrink its size and modify the color scheme (specifically, transitioning from a transparent background to white and altering font colors). Below is the HTML snippet: /* Defining the overa ...

Ensuring the checkbox is disabled prior to editing

Check out my table below: https://i.stack.imgur.com/7byIa.png Whenever I click the edit button, I can modify the status field and action field. This feature works correctly. However, the issue is that I am able to change the values of status and action e ...

Error: The global variable cannot be emptied due to an issue with the Ajax request

As someone who is relatively new to the world of Javascript/jquery and async, I have spent a significant amount of time reading through various forums. Unfortunately, I have yet to come across a solution that addresses my specific issue. The problem at ha ...

The condition will be false if a number is present, even if it is zero

I am facing an issue with a class containing an optional field called startDateHour: export class Test { startDateHour?: number; // more fields, constructor etc. } I need to perform an action only if the startDateHour exists: if (test.startDateHour ...

Simulate a keyboard key being pressed and held for 5 seconds upon loading the page

Is it possible to create a script that automatically triggers an event to press and hold down the Space key for 5 seconds upon page load, without any user interaction? After the 5 seconds, the key should be released. It is important to emphasize that abso ...