node.js – Node Js : How can Prevent jwt token for another logged in used not able to access current login user’s token
To prevent accessing data of one user with another user’s token, you can use JWT (JSON Web Token) and express-jwt library in your backend.
When a user logs in, you can generate a JWT token that includes the user’s ID as a payload. When the user makes a request to access their data, you can verify the JWT token and check if the user ID in the token matches the ID of the requested data.
Here is an example of how to use express-jwt to verify the JWT token:
const jwt = require('jsonwebtoken');
const expressJwt = require('express-jwt');
// set up JWT secret
const jwtSecret="your_jwt_secret";
// generate JWT token
const token = jwt.sign({ userId: user.id }, jwtSecret, { expiresIn: '1h' });
// verify JWT token with express-jwt middleware
app.get('/user-data', expressJwt({ secret: jwtSecret }), (req, res) => {
const userId = req.user.userId;
// check if userId matches requested data
if (userId === req.query.userId) {
// return user data
} else {
// return error response
}
});
In this example, the jwtSecret is the secret key used to sign and verify the JWT token. The token is generated with the jwt.sign method and includes the user ID as the payload.
When the user makes a GET request to /user-data, the express-jwt middleware verifies the JWT token using the jwtSecret. If the token is valid, the req.user object will include the decoded payload, which in this case is { userId: user.id }.
You can then check if the userId in the req.user object matches the requested data, and return the appropriate response.
Read more here: Source link
