2

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

3
  • Have you considered using Passport? There's a jwt strategy you could use. Commented Jun 26, 2018 at 20:08
  • Yeah, I have used passport in the past, I am actually not a big fan of it. For me, libraries that do too much of the work make it hard to customize and debug. Similar to using Rails in ruby, it's a great framework but when you need to have some custom use case or work flow, it becomes difficult to do what you want because it's so opinionated Commented May 3, 2019 at 13:23
  • I'd probably say Passport has all the available hooks that for a typical auth scenario you'd need....but over and above that, JS is pretty flexible in general, so there's usually never a problem extending libraries or frameworks to suit :) Commented May 3, 2019 at 15:16

1 Answer 1

3

Yes you pass the decoded into req

BUT

I would avoid setting decoded to req.user, simply because req.user is related to session user. Just use req.decoded or something else. You only need to use res.locals when you need to set the object globally to the rendering engine that you are using.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.