Reputation:
I did not find the doubt related to the nodejs.
I'm new to nodejs and I'm using the JWT framework to create user tokens and sessions. I would like to know how to protect against session attacks (stealing the user session with the token from it) and how do I actually protect access from the routes that need authentication.
At the moment my JWT code with authentication and routes is this:
JWT
const jwt = require('jsonwebtoken');
module.exports.sign = (userId, expiresInValue) => {
const userToken = jwt.sign({ userId }, process.env.SECRET, {
expiresIn: expiresInValue // EXPIRA EM 5 MINUTO
});
return userToken;
}
module.exports.tokenAuthentication = (req, res, next) => {
console.log(req.body.token)
if(!req.body.token){
res.status(401).send({
authStatus: false,
message: "NO TOKEN PROVIDED."
}).end();
} else {
jwt.verify(req.body.token, process.env.SECRET, (error, decoded) => {
if (error) {
res.status(200).send({
authStatus: false,
message: "FAILED TO AUTHENTICATE TOKEN."
}).end();
} else {
req.body.userId = decoded.userId;
req.body.userToken = req.body.token;
req.body.userTokenExp = "5 min";
next();
}
});
}
}
ROUTE EXAMPLE
const jwtLibrary = require('../../librarys/others/JWT');
module.exports = (app) => {
app.route('/home/v1/').post(jwtLibrary.tokenAuthentication, (req, res) => {
app.controllers.home.controller.renderHomePage(req, res);
});
}
ROUTER CONTROLLER EXAMPLE
module.exports.renderHomePage = (req, res) => {
res.render('home/view', {
JWT: {
userId: req.body.userId,
userToken: req.body.userToken,
userTokenExp: req.body.userTokenExp
}
});
}
Upvotes: 2
Views: 112
Reputation: 1354
If you issued a JWT token to a user, and then it is stolen by another user, there is no way to identify who uses the token (without a database). For that, I suggest your JWT tokens have short TTL(time to live)
.
On the other hand, because invalidating JWT tokens is an important issue for security perspective, you should use a database to keep the track of tokens. Personally, I use Redis
(a mem-cache db) to store JWT tokens because it is fast and suitable for that purpose. In that structure, you need to query Redis for every request to understand if the token is valid.
-Basically, you just need to delete tokens from the database.
I use this package https://www.npmjs.com/package/redis-jwt
You need to use refresh tokens which have greater TTL compared to authentication tokens. With this refresh token, you can issue a new authentication token once an auth token expires. Keep the refresh tokens in your normal database (MongoDB, SQL, Postgre or whatever). Also, know that refresh tokens have nothing to do with security. They don't bring any more security to the system. They are only used to issue a new auth token.
Upvotes: 1