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;