Confusion surrounding JWT authorization middleware

After reviewing the authentication middleware code in a course I am currently taking, I have some concerns about its security.

I decided to test a protected route using Postman and discovered that I was able to retrieve an order for one user with a token generated for another user.

const protected = asyncHandler(async (req, res, next) => {
  let token;
  if (
    req.headers.authorization &&
    req.headers.authorization.startsWith("Bearer")
  ) {
    try {
      token = req.headers.authorization.split(" ")[1];
      const decoded = jwt.verify(token, process.env.JWT_SECRET);
      req.user = await User.findById(decoded.id).select("-password");

  next();
} catch (error) {
  console.error(error);
  res.status(401);
  throw new Error("Not authorized, token failed");
}
 }
  if (!token) {
    res.status(401);
    throw new Error("Not authorized, No token found");
  }
}); 
export protected

It appears that this middleware only checks if a user from the decoded token exists in the database but does not restrict access based on the user/token.

import {addOrderItems, getOrderbyId}  from "../controllers/orderController.js";
import { protected } from "../middleware/authMiddleware.js";
    
const router = express.Router();

router.route("/").post(protected, addOrderItems);
router.route("/:id").get(protected, getOrderbyId);
//:id is the order id

However, when I tested another protected route for updating a user's profile information, I encountered an error when using an incorrect token.

I am seeking clarification on this matter.

Answer №1

When jwt.verify is used, it specifically verifies if the token provided was generated by the server, regardless of which user submitted the token.

In the case of protected middleware, its purpose is to check if a request is authorized. If it is, the request is then forwarded to the controller for further processing.

For handling an updating route, the implementation may look something like this:

// Update route 
router.route("/:userId", verifyToken, updateProfileController)

const updateProfileController = (req, res) => {
  const authorizedUser = req.user; // User obtained from the verification process
  const requestedUserId = req.params.userId; // User ID sent in the request
  
  if (authorizedUser.id !== requestedUserId) {
      // If the IDs do not match, it indicates an attempt to update the profile with an incorrect token
      res.status(401);
  }

  // Updating the profile in the database
}

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

What is the best way to find and run a binary file installed by one of my NPM package's dependencies?

I am currently working with an NPM package that has a dependency on node-pg-migrate. To properly function, my package needs to execute node-pg-migrate's binary pg-migrate. My environment is running node version 0.12.13. If the application where I ins ...

Turn off the interconnected route while utilizing npm to display the tree of dependencies

If I want to display the project's dependencies tree using npm, I would use the following command: npm ls lodash The output will look something like this: > npm ls lodash npm info using [email protected] npm info using [email protected] ...

Issue with setting cookies in Node.js using Express

Recently I made the switch from regular JavaScript to TypeScript for my project. Everything seems to be functioning properly, except for session handling. This is the current setup of my project: Server.ts App.ts /db/mongo/MongoHandler.ts and some other ...

Node(Meteor) experiencing a memory leak due to setTimeout

I have encountered an unusual memory leak associated with the use of setTimeout. Every 15 seconds, I execute the following code using an async function that returns an array of promises (Promise.all). The code is supposed to run again 15 seconds after all ...

Is there a way to consistently substitute a specific path parameter with a different value within node.js?

Snippet of my coding: router.get('/name/:name/height', (req,res) => { ... } router.get('/name/:name/weight', (req,res) => { ... } router.get('/age/:age/height', (req,res) => { ... } router.get('/ag ...

Having issues with installing @angular/cli globally using npm on Windows 7, the process gets stuck and does not

Encountering an issue while attempting to install the Angular CLI from npm, as it gets stuck asking to loadAllDepsIntoIdealTree. Here are the steps taken: C:\Windows\system32\node -v v6.11.1 C:\Windows\system32\npm -v 3.1 ...

Difficulty encountered while executing Protractor tests with Selenium Server

Attempting to Execute Protractor/Jasmine/Selenium End-to-End Tests Currently in the process of running end-to-end tests using Protractor with the standalone Selenium server and the chrome driver. Encountering a Selenium server error when attempting to ru ...

Are you ensuring compliance with licensing in your Webpack bundles?

Can webpack be used to verify license compliance? I'm looking for a way to ensure that the license headers from all modules built by webpack are included in the final output file. How can we confirm this is happening? Furthermore, I am also intereste ...

Trouble With $and Operator in Mongoose's findOne Method

BorrowBookSchema const borrowBookSchema = new mongoose.Schema({ member_id : { type : String, required: true, }, member_name : { type : String, required : true }, bookdetails : [{ bookid : String, ...

You can only set headers once during the initial request; any additional attempts to set headers will result in an

I encountered a specific issue with the error message "Can't set headers after they are sent". Here is the relevant code snippet: create: (request, response, next) -> socket = @app.socket # # This method will be used to call the right method ins ...

Executing a Node.js script to switch the current directory in the command prompt

I am facing an issue while trying to change the terminal directory using a Node.js program. Even after running the script as node app.js dir_name, I am unable to successfully switch to the created directory. The directory gets created but the terminal do ...

The Jenkins build process is encountering errors while trying to generate lighthouse reports

Fri, 28 May 2021 09:27:18 GMT ChromeLauncher Waiting for browser............................................................................................. Fri, 28 May 2021 09:27:19 GMT ChromeLauncher Waiting for browser.................................. ...

Having trouble with the installation of packages using the Node Package Manager on Ubuntu

Ubuntu has renamed the NodeJS interpreter name (node) to nodejs due to a conflict with another package. The Debian readme states: The original name for the Node.js interpreter command is "node". In Debian, it was changed to "nodejs". This change was ...

How can I navigate through embedded MongoDB documents in Node.js to retrieve the values of their keys?

I'm facing an issue with multiple MongoDB documents related to each other. I need help accessing keys and values from the parent document down to the grandchild relational document. Here's the structure I have: const itemSchema = new mongoose.Sch ...

Using Firebase Admin or the regular Firebase with Next.js

Currently, I am working on a project using Next.js and integrating Firebase. I have been successfully fetching data in my components using the Firebase package designed for frontend use. However, I recently attempted to utilize Firebase within getServerS ...

Convert the nodejs undefined into bindings.js within an Electron project (and utilize better-sqlite3)

My Electron.js project setup includes the following steps: Installing node 14 Installing vue-cli Creating a template project in Vue with: vue create myproject Adding an Electron wrapper like this: vue add electron builder Installing the better-sqlite3 lib ...

The process of examining a function that includes the invocation of an additional API function in a NodeJS environment

I'm faced with a situation where I have a nested function inside another function. The second function is responsible for making an API call. However, in order to write a unit test for this scenario, I need to avoid actually making the real API call a ...

The npm package installation process encountered difficulties in accessing the Chart.Js library

Currently, I am in the process of developing a web application that tracks and logs hours spent on various skills or activities. The data is then presented to the user through a bar graph created using Chart.js. Initially, I was able to display a mock grap ...

Establishing a server-side connection with Socket.io using Node.js

In my Node.js application, I have a frontend app and a backend app. The backend is responsible for managing the list and pushing updates to the frontend app. When I make a call to the frontend app, it triggers a list update so that all clients receive th ...

Efficient - Serving a CSV file from a distant server: A comprehensive guide

Currently, I am working on a simple node/express API with just one route. The main objective of this route is to make an API request to a third-party service that provides a CSV file. My goal is to then send this CSV file back as a response. While I have ...