【问题标题】:Cannot hash password with bcrypt无法使用 bcrypt 散列密码
【发布时间】:2019-07-17 23:25:36
【问题描述】:

我一直在尝试在我的用户中实现 bcrypt,以便可以使用 JWT 进行身份验证;但是,每当我尝试使用 bcrypt 对密码进行哈希处理时,它都会在第一个 if 语句中抛出错误。我使用 express.js 作为我的框架。我还必须提到我没有使用数据库,并且用户存储在不同文件的数组中。我是 node 新手,我仍在努力理解它。

我的用户路线

const express = require('express');
const router = express.Router();
const users = require('../../Users');
const bcrypt = require('bcrypt');

router.post('/signup', (req, res, next) => {
    bcrypt.hash(req.body.password, 10, (err, hash) => {
        if (err) {
            return res.status(500).json({
                error: err
            });
        } else {
            const user = {
                id: users.length + 1,
                userName: req.body.userName,
                email: req.body.email,
                password: hash,
                firstName: req.body.firstName,
                lastName: req.body.lastName,
            }
            user
                .then(result => {
                    console.log(result)
                    res.status(201).json({
                        message: 'User created'
                    })
                })
                .catch(err => {
                    console.log(err);
                    res.status(500).json({
                        error: err
                    });
                })
        }
    })
})

客户请求

{
    "email": "test@test.com",
    "password": "testerpassword",
    "userName": "test",
    "firstName": "teste",
    "lastName": "tester"
}

【问题讨论】:

  • 您不使用护照的任何原因。使用护照和为您做所有事情的策略会更好/更容易。
  • 护照还没看,我试试看。
  • 解决方案是使用经过测试和证明的框架,而不是构建自己的框架。示例在网站上。
  • @jcuypers 我不认为我可以使用护照,因为我没有使用数据库。
  • @razvanusc 好的,你不是错误检查输入或什么都没有。尝试用固定的字符串值替换 req.body.password 并查看错误是否消失或移动。或者只是在尝试之前尝试控制台记录该值。我们需要确保值已定义。

标签: node.js express jwt bcrypt


【解决方案1】:

制作一个获取密码并返回并加密的辅助方法:

const crypto = require("crypto");
const hashThePassword = (str) => {
  if (typeof str == "string" && str.length > 0) {
    const hash = crypto
      .createHmac("sha256", config.hashingSecret)
      .update(str)
      .digest("hex");
    return hash;
  } else {
    return false;
  }
};

配置对象包含任意秘密字符串。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-04
    • 2016-12-11
    • 2021-01-09
    • 2013-04-24
    • 1970-01-01
    • 2019-07-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多