0

my problem is I can store all the login details in MongoDB. and when I log a user I get the token but I'm not sure to do the logout functionality.

login

 router.post("/admin/sign_in", async (req, res) => {
  try {
     const { email, password } = req.body;

    if (!(email && password)) {
      res.status(400).send("All input is required");
    }
    const user = await User.findOne({ email });

    if (user && (await bcrypt.compare(password, user.password))) {
      const token = jwt.sign(
        { user_id: user._id, email },
        process.env.TOKEN_KEY,
         {
          expiresIn: "15h",
        }
      );

      user.token = token;

      return res.status(200).json(user);
    }
  } catch (err) {
     return res.status(400).send("Invalid Credentials");
  }
});
module.exports = router;

authentication

const jwt = require("jsonwebtoken");

const config = process.env;

const authenticate = (req, res, next) => {
  const token =
    req.body.token || req.query.token || req.headers["autherization"];

  if (!token) {
    return res.status(403).send("A token is required for authentication");
  }
  try {
    const decoded = jwt.verify(token, config.TOKEN_KEY);
    req.user = decoded;
  } catch (err) {
    return res.status(401).send("Invalid Token");
  }
  return next();
};

module.exports = authenticate;

here I have all the functionality working fine and I need an idea to implement the logout functionality

sumanth
  • 318
  • 1
  • 6
  • 25
  • Is your token stored in Mongodb? – Charchit Kapoor Nov 03 '22 at 06:28
  • @CharchitKapoor no, the token is not stored. – sumanth Nov 03 '22 at 06:31
  • 1
    The answer is unfortunately not easy. JWTs are used to store session information on client side. Of course you can just remove the JWT from `localStorage` or whereever you store it in your client, but the token will still be valid. Maybe the accepted answer in this post will help you to determine a strategy, which is suitable for you: https://stackoverflow.com/questions/21978658/invalidating-json-web-tokens – Fabian Strathaus Nov 03 '22 at 06:57

1 Answers1

1

Let's look at what is the most basic thing that should happen when a user logs out.

The most basic thing is that the jwt-token should be invalidated. So, all the new requests from that invalidated token should fail at the authenticate middleware.

Now, for the authenticate function to fail for the invalid tokens, it should somehow determine that the token is invalidated due to logout, other than using jwt.verify method, because jwt.verify won't fail until the token expires, but the logout can happen before that. That's why you need to have some sort of persistent storage to determine whether the tokens are valid or not. Normally, in-memory stores like Redis, and Memcached are used for it.

Here's one of the things you can do:

  1. On sign-in, store the token in Redis.
  2. In authenticate function, along with jwt.verify, you should check if that token is present in Redis, only then allow the request to go forward.
  3. On logout, delete the token from Redis, this will ensure that all incoming requests with that token, start failing.

For more approaches, the answer link in the comment by @Fabian Strathaus will also give some great suggestions.

Charchit Kapoor
  • 8,934
  • 2
  • 8
  • 24