Rest API – 在JSON响应中获取密码是安全的吗?

我正在用Node.js编写Rest API,并使用JWT。

我有下面的路线来validation用户。

我想问,从User.findOne方法返回的用户返回正确的密码,因此我能够检查它是否正确。 但是,这是安全的吗? 我做了一个console.log,并显示密码(尽pipeencryption),但仍然感到不安全,因为有人可以肯定地查看?

 router.post('/authenticate', function(req, res) { // find the user User.findOne({ name: req.body.name }, function(err, user) { if (err) throw err; if (!user) { res.json({ success: false, message: 'Authentication failed. User not found.' }); } else if (user) { // check if password matches if (user.password != req.body.password) { res.json({ success: false, message: 'Authentication failed. Wrong password.' }); } else { // if user is found and password is right // create a token var token = jwt.sign(user, app.get('superSecret'), { expiresInMinutes: 1440 // expires in 24 hours }); // return the information including token as JSON res.json({ success: true, message: 'Enjoy your token!', token: token }); } } }); }); 

没有。

此外,密码不应该在数据库中被encryption保存,而是被散列 。 古典环境例如将密码保存为md5(更常见)或bcrypt(更安全)的散列。

这样可以确保即使数据库被盗,也不会有用户的密码。 没有办法“解密”哈希(而不是一亿年)。

当用户login时,将input密码的散列与用户分配的散列进行比较。 你可以使用像bcrypt-nodejs这样的好模块

编辑

从技术angular度来看,这不会是危险的。 当你启动你的服务器时,JavaScript会编译你的代码并在V8引擎中执行结果。 只要节点和MySQL之间的连接保存,就无法访​​问数据库返回的内容。 有人可能会转储服务器内存,并希望find正确的位。 但是,如果有人获得必要的权限,你注定要么。

我为你实施了一个例子,它没有经过testing,但应该告诉你这是怎么回事。

 router.post('/register', function(req, res) { bcrypt.hash(req.body.password, null, null, function(err, hash) { if (!err) { var newUser = new User({ name: req.body.name, password: hash }); newUser.save(); // ???? } }); }); router.post('/authenticate', function(req, res) { User.findOne({ name: req.body.name }, function(err, user) { var password = 'GP%Z!zvbk/9>Ss-R'; var passwordHash = '$2a$10$W.zZPCaNOuR152I4qENKH.8h7I6BPcfCYBJqHPNXbVaBz0XWVxnBm'; // bcrypt of string ')RZK&M(QX"k188cw' if (user) { password = req.body.password; passwordHash = user.password; } bcrypt.compare(password, passwordHash, function(err, success) { if (success) { var token = jwt.sign(user, app.get('superSecret'), { expiresInMinutes: 1440 }); res.json({ success: true, message: 'Enjoy your token!', token: token }); } else { res.status(401).json({ success: false, message: 'Authentication failed.' }); } }); }); }); 

注意:对于每个散列操作,bcrypt默认使用随机盐。 这意味着,无论何时您对给定的input进行哈希处理,每次都会产生不同的哈希值。 然后将盐存储为散列的一部分,然后可以对其进行validation。 请查看维基百科进一步的信息。