cedada31
cedada31

Reputation: 1

Big problem with security (JWT NodeJS), one token for all acces

I have a really big problem with security in my web application. I implemented JWT token when user login to my application (REST API returns token).

In my jwt token, I have only userID. Problem is that, when I would like to login on user with ID = 1,

I can see and execute rest actions from all other users with the same token. for example:

When I looged userId = 1, I doing GET action: /api/users/1 and I have a information about user 1. But I can doing action /api/users/2, 3 etc.

All with one token. how to secure it?

const jwt = require('jsonwebtoken');
const env = require('../config/env.config.js');

module.exports = (req, res, next) => {
  try {
    const token = req.headers.authorization.split(' ')[1];
    const decoded = jwt.verify(token, env.SECRET_KEY);
    req.userData = decoded;
    next();
  } catch (error) {
    return res.status(401).json({
      message: 'Auth failed',
    });
  }
};

Upvotes: 0

Views: 60

Answers (1)

Gor Kotikyan
Gor Kotikyan

Reputation: 723

I think the best solution would be to create middleware that check the id of the sender and attach it to routes, similar to bellow

const middleware = (req, res, next) => {
  const id = req.params.id || req.body.id || req.query.id
  if (req.userData.id === id) {
    next()
  } else {
    res.status(403).send({message: "forbidden"})
  }
}
router.get("/api/users/:id", middleware, (req, res) => {
  // do your staff
  res.send({message: "ok"})
})
router.put("/api/users/:id", middleware, (req, res) => {
  // do your staff
  res.send({message: "ok"})
})

Upvotes: 2

Related Questions