简体   繁体   中英

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',
    });
  }
};

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"}) }) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM