【问题标题】:Invalid Credentials Bcyrpt.compare()无效的凭证 Bcyrpt.compare()
【发布时间】:2021-02-25 04:15:43
【问题描述】:
    const express = require('express');
const router = express.Router();
const auth = require('../../middleware/auth');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const config = require('config');
const { check, validationResult } = require('express-validator');
 
 
const User = require('../../models/User');
// @route Get api/auth
// @desc Test route
// @access Public
router.get('/', auth, async (req, res) => {
 
 
  try {
    const user = await User.findById(req.user.id).select('-password');
    res.json(user);
  } catch(err) {
    console.error(err.message);
    res.status(500).send('Server Error')
  }
});
 
 
// @route POST api/auth
// @desc Authenticate User And Get Token
// @access Public
router.post('/',
[
  check('email', 'Please include a valid email').isEmail(),
  check('password', 'Password is required').exists()
],
 
async (req, res) => {
 
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.array()});
  }
 
  const { email, password } = req.body;
 
  try {
    // See if user exists
      let user = await User.findOne({ email})
 
      if (!user) {
        return res
        .status(400)
        .json({ errors: [ { msg: 'Invalid Credentials Email' } ] });
      }
 
 
    // Make Sure Password matches
      const isMatch = await bcrypt.compare(password, user.password);
 
      if(!isMatch) {
        return res
        .status(400)
        .json({ errors: [ { msg: 'Invalid Credentials Password' } ] });
      }
 
 
 
      const payload = {
        user: {
          id: user.id
        }
      }
 
      jwt.sign(
        payload,
        config.get('jwtSecret'),
        { expiresIn: 360000 },
        (err, token) => {
          if(err) throw err;
 
          res.json({ token });
        }
        );
  } catch(err) {
    console.error(err.message);
    res.status(500).send('Server error')
  }
 
 
});
 
module.exports = router

在我的数据库中,我有电子邮件和密码 当我向 https://localhost:5000/api/auth 发出 POST 请求时,在我的邮递员中

电子邮件是正确的,但是我不断收到密码不正确,这个 const isMatch = await bcrypt.compare(password, user.password);

  if(!isMatch) {
    return res
    .status(400)
    .json({ errors: [ { msg: 'Invalid Credentials Password' } ] });
  }

我控制台记录了密码和 user.password 并且它是相同的值,我不明白为什么 !isMatch 不断被触发

谁能帮帮我

【问题讨论】:

  • 当你说“我控制台记录了密码和 user.password 并且它是相同的值”时,你是什么意思。你在哪里记录的?

标签: javascript node.js mongoose bcrypt


【解决方案1】:

bcrypt.compare()的语法是:

bcrypt.compare(plaintextPassword, hash)...

第一个参数是明文密码,第二个是真实密码的哈希值,所以不会是同一个值。正如您所提到的,您的 passworduser.password 是相同的值,我猜您在将其保存到数据库之前忘记了对用户密码进行哈希处理。详情请查看docs

【讨论】:

    猜你喜欢
    • 2016-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-26
    • 1970-01-01
    • 2021-12-17
    • 2018-07-09
    • 1970-01-01
    相关资源
    最近更新 更多