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

Learn how to retrieve information using the dash operator in ReactJS

I find it a bit amusing, but I'm encountering an issue. Can anyone lend me a hand with this? So, I'm using an API to fetch some data and it appears that the response from the API is in this format: start-time:2323232 end-time:2332323 Now, when I ...

Unauthorized access detected during ajax request triggered by onpaste event

Recently, I encountered an issue with my asp.net mvc website where an ajax call to the server stopped working in IE 11, despite previously working fine in IE 8. The error message pointed to an access denied exception in jQuery 1.7.1 at h.open(c.type,c.url, ...

Equal size images displayed within cards in Material UI

Is there a way to create a list of Material UI components with images that have uniform height, even if the original images vary in size? I want to make all image heights responsive and consistent across all cards. Any suggestions on how to achieve this? ...

JQuery is unable to initiate a keyup event

I am currently utilizing jQuery in a web application. On one of my pages, I have set up an event listener for keypresses as shown below: document.addEventListener('keyup', function (event) { event.preventDefault(); var key = event.k ...

Converting an HTML table into an Excel spreadsheet

In the process of developing an application that populates a table based on a JSON dataset, I am seeking a way to store the filtered data into an Excel file or even a CSV. The structure includes two script files - app.js and mainController.js (organized fo ...

Press anywhere outside the slide menu to close it using Javascript

Hey, I've looked around and can't find a solution to my issue. I have a javascript menu that currently requires you to click the X button to close it. I want to be able to simply click anywhere outside the menu to close it instead. <head> ...

Empty Canvas: Google Charts Graph Fails to Populate

I am currently using mysql, php, and javascript to display a curve chart. The issue I am facing is that the chart appears blank. google.load('visualization', '1.0', {'packages':['corechart']}); google.setOnLo ...

There was an error: at.a is undefined

I am experiencing a perplexing issue with my Vue 2 web app that utilizes AWS Amplify. Strangely, a similar app I have is functioning perfectly in every respect, but this one refuses to work in production. During development on my local machine, everything ...

Is there a way to retrieve the value from a select tag and pass it as a parameter to a JavaScript function?

I would like to pass parameters to a JavaScript function. The function will then display telephone numbers based on the provided parameters. <select> <option value="name-kate">Kate</option> <option value="name-john">John& ...

The issue of memory leakage with ng-grid and real-time data

My intention is to utilize ng-grid for visualizing high-frequency real-time data, but I am encountering issues with a memory leak. Interestingly, the memory leak does not occur when I opt for a simple HTML table with ng-repeat. My tech stack includes node ...

You need a function property for the child component to be updated

I recently encountered an unusual issue with my React components that has left me puzzled. Here is a condensed version of the app: class Child extends React.Component { componentDidUpdate(prev) { if (!prev.isActive && this.props.isActive) ...

What is the best way to cycle through a nested JS object?

I am currently utilizing useState and axios to make an API call, retrieve the response, and pass it to a Component for rendering. const [state,setState] = useState([]); const getCurrData = () => { axios.get('working api endpoint url').then(r ...

Tips on causing JavaScript execution to halt until an element has finished rendering

test.view.js timeDBox = new sap.ui.commons.DropdownBox({layoutData: new sap.ui.layout.GridData({linebreak: true}), change: function(oEvent){ oController.getKeyEqChart(); }, }), new sap ...

Angular is unable to detect the dynamically loaded page when using Extjs

Within my Extjs SPA system, I have integrated Angular along with the necessary modules to be used on a page that is being referred in an external HTML panel in Extjs. While Angular is defined and functioning properly everywhere else, it seems to not work ...

Use the npm-search feature to show only the name and description columns in the search results

After running the command npm search packagename, I noticed that the results are shown in 6 columns: name, description, author, date, version, and keywords. Is there a way to customize npm-search so that it only displays the name and description columns? ...

Securing your route with Mocha Chai testing

I am currently working with an Express server and utilizing passport-local for authentication. One of my protected routes looks like this: app.post("/api/test", connect.ensureLoggedIn("/"), (req, res) => { let test = new Test(req.body); test .save() ...

Guide to creating fog animations in three.js

I'm attempting to adjust the fog density using tweening, but for some reason, it doesn't seem to be working. Here are my default settings: var camera, densityFog, colorFog2; colorFog2 = 0xfee2ed; densityFog ...

Tips for maximizing the benefits of debounce/throttle and having a truly dynamic experience

Attempting to implement a similar concept in Vue: props(){ debouncing: {type: Number, default: 0} }, methods: { clicked: _.debounce(function() { this.$emit('click'); }, this.debouncing), } Unfortunately, the code breaks when ...

Navigate to a specified div using JavaScript

I'm having an issue with my navigation bar not scrolling to the designated div. Despite looking at other examples, I can't seem to find a solution <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> ...

Is the query generated safely and protected from SQL injection threats?

I am currently working on developing a search bar that can handle multiple words, but I am concerned about the risk of SQL injection. My technology stack includes node express using the npm mssql package. Below is the code snippet I have implemented to t ...