I am trying to find a solution where I can have a middleware check on a route that verifies the JWT. Since this verification decodes it as well as verifying, I would like to pass the decoded data along to the route without having to decode again. See my current solution below:
//route.js
app.get("/donations", helpers.protected, (req, res) => {
console.log(req.user)
});
//helper.js
module.exports.protected = (req, res, next) => {
const jwt_token = req.cookies["auth"];
jwt.verify(jwt_token, nconf.get("jwt:secret"), (err, decoded) => {
if (err || !decoded) {
logErr(error.INVALID_JWT, err, req);
return res.redirect("/");
} else {
req.user = decoded;
return next();
}
});
};
The goal is to keep code simple and clean in the routes by putting validation logic in a middle function. I want to be able to prevent having to decode twice but also be secure. Can I use req.user = decoded; as I have shown above? Can req.user ever be modified or placed in a HTTP request from the client? Would using res.locals.user = decoded; be any better or worse to use?
Thank you