Failure to process JsonWebTokenError due to a corrupted signature in the middleware

I am facing an issue with my middleware when the

jwt.verify(request.token, process.env.SECRET)
function raises a
JsonWebTokenError: invalid signature with middleware
error upon receiving an invalid token. Despite configuring my middleware correctly, this error is causing my application to crash.

The error specifically occurs in the blogs.js file while attempting to add a new blog using an invalid token:

blog.js:

const jwt = require("jsonwebtoken");
const blogsRouter = require("express").Router();

const Blog = require("../models/blog");
const User = require("../models/user");

blogsRouter.post("/", async (request, response) => {
    const body = request.body;

    const decodedToken = jwt.verify(request.token, process.env.SECRET);
    if (!decodedToken.id) {
        return response.status(401).json({ error: "token invalid" });
    }
    const user = await User.findById(decodedToken.id);

    const newBlog = new Blog({
        title: body.title,
        author: body.author,
        url: body.url,
        likes: body.likes || 0,
        user: user.id,
    });

    const savedBlog = await newBlog.save();
    user.blogs = user.blogs.concat(savedBlog._id);
    await user.save();

    response.status(201).json(savedBlog);
});

module.exports = blogsRouter

middleware.js:

const unknownEndpoint = (request, response) => {
    response.status(404).send({ error: "unknown endpoint" });
};

const errorHandler = (error, request, response, next) => {
    logger.error(error.message);

    if (error.name === "CastError") {
        return response.status(400).send({ error: "malformatted id" });
    } else if (error.name === "ValidationError") {
        return response.status(400).json({ error: error.message });
    } else if (error.name === "JsonWebTokenError") {
        return response.status(401).json({ error: "invalid token" });
    } else if (error.name === "TokenExpiredError") {
        return response.status(401).json({
            error: "token expired",
        });
    }
    
    next(error);
};

const tokenExtractor = (request, response, next) => {
    const authorization = request.get("authorization");
    if (authorization && authorization.startsWith("Bearer ")) {
        request.token = authorization.replace("Bearer ", "");
    }
    next()
}

module.exports = { requestLogger, unknownEndpoint, errorHandler, tokenExtractor };

app.js:

const express = require("express");
const app = express();
const cors = require("cors");
const mongoose = require("mongoose");
const config = require("./utils/config");
const logger = require("./utils/logger");
const middleware = require("./utils/middleware");

const blogsRouter = require("./controllers/blogs");
const usersRouter = require("./controllers/users");
const loginRouter = require("./controllers/login");

mongoose.set("strictQuery", false);

mongoose
    .connect(config.MONGODB_URI)
    .then(() => {
        logger.info("connected to MongoDB");
    })
    .catch((error) => {
        logger.info("error connectig to MongoDB", error.message);
    });

app.use(cors());
app.use(express.json());
app.use(middleware.tokenExtractor)

app.use("/api/blogs", blogsRouter);
app.use("/api/users", usersRouter);
app.use("/api/login", loginRouter);

app.use(middleware.errorHandler);

module.exports = app;

Answer №1

To handle invalid tokens, you can enclose the jwt.verify function within a try-catch block and return an error message if the token is not valid.

blogsRouter.post("/", async (request, response) => {

        const body = request.body;
        try {
            const decodedToken = jwt.verify(request.token, process.env.SECRET);
            if (!decodedToken.id) {
                return response.status(401).json({ error: "token invalid" });
            }
            const user = await User.findById(decodedToken.id);
    
            const newBlog = new Blog({
                title: body.title,
                author: body.author,
                url: body.url,
                likes: body.likes || 0,
                user: user.id,
            });
    
            const savedBlog = await newBlog.save();
            user.blogs = user.blogs.concat(savedBlog._id);
            await user.save();
    
            response.status(201).json(savedBlog);
        } catch (e) {
            return response.status(401).json({ error: "token invalid" });
    
        }
    });

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

Encountering a "variable not found" error when trying to run the JavaScript code to manipulate the web element

Upon executing the command to change the value of a web element text, I encountered an error stating "Can't find variable: e." sel=webdriver.PhantomJS() sel.get=('http://stackoverflow.com/questions?pagesize=50&sort=newest') elements=sel ...

Input field for postal code containing only numbers (maximum 5 digits) in Angular version 4/5

I am struggling with creating an input field that accepts numbers. If I use type="text", I can only type 5 characters of alphanumeric data, but if I use type="number", it allows any number input without limiting it to just 5 numbers. Thank you in advance f ...

Enhance text by hovering over it

I am currently working on implementing a unique feature using jQuery and CSS. Rather than just inheriting the width, I want to create a magic line that extends to the next index item. Scenario: 1: Hover over Element one ELEMENT ONE ELEMENT TWO ELEM ...

Express.js presents a challenge when it comes to managing permissions in its architecture

While developing an app on Express.js, I encountered a challenging architectural issue related to permissions. Some example resources include: Organisation, user, unit, resource Each user may be associated with multiple organisations, each organisation c ...

Combining various postponed JavaScript file imports in the HTML header into a single group

I've been facing an issue with my code structure, particularly with the duplication of header script imports in multiple places. Every time I need to add a new script, I find myself manually inserting <script type="text/javascript" src=&q ...

How can we effectively create a table page object in Protractor that can handle various table selectors?

Recently, I have been delving into writing e2e tests in Protractor using page objects with JavaScript/Node.js. After reading numerous Stack Overflow posts and Julie's pages, as well as studying ProtractorPageObjects, I've come across an issue. A ...

Is there a way to adjust the width of a table cell in Material UI using React?

I encountered a problem where I am attempting to adjust the width of a table cell, specifically in Typescript. However, I am only able to choose between medium and small sizes for TableCellProps. Is there a workaround for this issue? I am looking to expand ...

The playwright brings the curtain down on a blank page without a single word

I am working with code snippets const {chromium} = require('playwright'); (async () => { const userDataDir = '\NewData'; const browser = await chromium.launchPersistentContext(userDataDir,{headless:false}); const pag ...

I am interested in incorporating dynamic fields within the mongoose schema

Currently, I am working with MongoDB using Mongoose, Node.js with Express, and React. I have a requirement to develop a feature where users can create collections. Within these collections, they should be able to add products corresponding to each collect ...

Delaying http requests until cache is fully prepared without the need for constant checking

In a unique scenario I am facing, my http requests are caching intermediary results on the server. If the cache is not found, then another server is requested to build it. These requests are sent consecutively (in a loop) using AJAX to a Node Server, with ...

Guide on sending files and data simultaneously from Angular to .NET Core

I'm currently working on an Angular 9 application and I am trying to incorporate a file upload feature. The user needs to input title, description, and upload only one file in .zip format. Upon clicking Submit, I intend to send the form data along wit ...

Vercel and Firebase Realtime Database causing snapshot.val() to return null during build deployment

Creating a blog application using Next.js, Firebase Realtime Database, and Vercel for hosting has been seamless on my local machine. Even after running npm run build, everything functions perfectly. However, when deployed to Netlify in production, the snap ...

Creating a Vuejs index page through Node and Express: A step-by-step guide

I am currently developing a small application using Vuejs + Node, but I am facing the challenge of running 2 servers during development: Firstly, my node server: nodemon server.js Secondly, the Vuejs built-in script: npm run dev, which runs webpack-dev-s ...

Retrieving the selected date from mat-datepicker into a FormControl

When creating a POST request to an API, I encountered an issue with the mat-datepicker field as it throws an error when inside the ngOnInit() call (since nothing is selected yet). Other fields like name, email, etc. work fine, but extracting a value from t ...

What is the routing file utilized by my express/angular application? And which one holds the higher priority?

After creating a basic single page express app with Angular, I'm curious about which routes file my application is utilizing and the reasoning behind it. Here's the link to my repo: here In my repository, there's a node routes.js file loca ...

I am encountering an issue with the material ui dropdown component in my react native app where I am receiving a TypeError stating that it cannot read the property 'style' of undefined. This error is likely caused

Upon installation of Material UI and importing The Dropdown component, I encountered the error TypeError: Cannot read property 'style' of undefined, js engine: hermes. This is my code import React, { useEffect, useState } from "react"; import { ...

Implement the insertion of ObjectId data into the response in a node/express application

While using postman to insert an ObjectId, I encountered an error when setting the Content-Type header to multipart/form-data. The error message I keep receiving is: { "errors": { "singer": { "message": "Cast to ObjectID failed fo ...

Tips for enabling auto-scroll feature in MuiList

Currently, I am working on a chat window component that utilizes Material UI for styling. I expected that setting a height or max-height on either the MuiList or MuiBox encapsulating the list would automatically scroll to the new message when it's sen ...

Event emitting from a parent Vue.js component

I can't figure out why my code is not functioning properly. I have an event called 'leave' that should be triggered on blur. The components show up correctly, but the event doesn't fire when leaving the inputs. Vue.component('te ...

Issue: Reactjs - Material-UI HTML Tooltip does not display dynamic HTML content.In the Reactjs

I have been using a customized HTML MUI Tooltip. Currently, it is functioning with static content but I am looking to make it dynamic. Unfortunately, it is not working with dynamic HTML content. Here is my attempted approach: const ADJUSTMENT_HELP_TEXT = ...