2

I quite a beginner and used a tutorial for authentication. I am using jwt and based on that tutorial I have added a middleware. I dont know/think its right:

  1. Since im using jwt, I am validating the token in my middleware, all correct. However Im also taking the userid from payload, making a request to the db and if i find a user, i put it on req.user. Am I not failing the whole point of using jwt then? Is not the point in using jwt to not make every time a request to the db?
  2. This is not related to using jwt, but in case my middleware is fine, when there is no db connection, at the point where Im fetching user from db, I get an err which makes sense, but somehow the error is not not handled, even though I do have a catch. Am I doing it wrong? Thank you!

module.exports = (req, res, next) => {
    const { authorization } = req.headers;
    try {

        if (!authorization) return res.status(401).send({error: 'you must be logged in'})
        const token = authorization.replace('Bearer ', "");

        jwt.verify(token, 'MY_SECRET_KEY', async (err, payload) => {
            if (err) return res.status(401).send({error: 'you must be logged in'})

            const {userId} = payload;
            const user = await User.findById(userId);

            if (user)  req.user = user;
            else return res.status(401).send({error: 'you must be logged in'})
            next();
        })
    } catch (err) {
        res.status(400).send("too bad its an err")
    }
};
learncode
  • 127
  • 6

1 Answers1

0

Am I not failing the whole point of using jwt then? Is not the point in using jwt to not make every time a request to the db?

Trust your jwt. If you can't trust the data in your JWT then you may have a security problem. Verifying the user by calling the DB each time makes using a stateless authentication almost pointless.

If the user data or the data that your payload contains are subject to many changes you could implement a refreshToken and give the ordinary token a short expiry (for example 1 hour) and then issue a new token using the refreshToken: at that moment, you make only one call to the db you need to validate the user and eventually update the payload.

If you need an even higher level of security, you can also think about encrypting the entire payload (this however will lengthen the encoding/decoding times).

Please take a look at this answers, too: JWT vs cookies for token-based authentication

Is it more efficient to store the permissions of the user in an JWT claim or to check it on the server at every request?

but somehow the error is not not handled, even though I do have a catch.

What do you mean by "somehow the error is not not handled"? It seems you are using Express as backend. Is the error catched by the parent function or inside a global handler? Please update your question with an example case and I'll update my answer.

crivella
  • 514
  • 5
  • 19