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
CodePudding user response:
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:
- On sign-in, store the token in Redis.
- In
authenticate
function, along withjwt.verify
, you should check if that token is present in Redis, only then allow the request to go forward. - 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.