javascript 比较密码BcryptJS

9cbw7uwe  于 2023-01-24  发布在  Java
关注(0)|答案(6)|浏览(227)

所以我试着建立一个非常基本的用户登录。我试着创建一个用户,然后用这些凭据登录并取回一个JSON Web令牌。我被卡住的地方是试着比较密码,然后发送一个响应。
步骤:
创建用户:
1.输入电子邮件和密码

  1. salt/hash用户密码
    1.将用户存储到数据库
    1.返回成功
    登录
    1.按请求电子邮件值查找用户
    1.如果找到,请比较密码
    1.密码正确发送JSON Web令牌
    • 用户模型**
email:{ 
  type: String,
  required: true,
  unique: true
},
password: {
  type: String,
  required: true
}
    • 用户路由**
var express     = require('express');
var router      = express.Router();
var jwt         = require('jsonwebtoken');
var bcrypt      = require('bcryptjs');

// Create User
...
bcrypt.genSalt(10, function(err, salt) {
    bcrypt.hash("superSecret", salt, function(err, hash) {
      user.password = hash;
      user.save();
      res.json({success: true, message: 'Create user successful'});
    });
  });
...

// Login
...
bcrypt.compare(req.body.password, 'superSecret', function(err, res) {
  if(req.body.password != user.password){
    res.json({success: false, message: 'passwords do not match'});
  } else {
    // Send JWT
  }
});

所以这里的两个问题是,我不能发送一个响应,也不能比较密码。只是完全停留在这一点上,任何帮助将不胜感激。

r1zk6ea1

r1zk6ea11#

doc中所述,应按如下方式使用bcrypt.compare

bcrypt.compare(req.body.password, user.password, function(err, res) {
  if (err){
    // handle error
  }
  if (res) {
    // Send JWT
  } else {
    // response is OutgoingMessage object that server response http request
    return response.json({success: false, message: 'passwords do not match'});
  }
});

这里有一篇关于Password Authentication with Mongoose (Part 1): bcrypt的好文章

jpfvwuh4

jpfvwuh42#

//required files
const express = require('express')
const router = express.Router();

//bcryptjs
const bcrypt = require('bcryptjs')

//User modal of mongoDB
const User = require('../../models/User')

//Post request for login
router.post('/', (req, res) => {
    //email and password
    const email = req.body.email
    const password = req.body.password

    //find user exist or not
    User.findOne({ email })
        .then(user => {
            //if user not exist than return status 400
            if (!user) return res.status(400).json({ msg: "User not exist" })

            //if user exist than compare password
            //password comes from the user
            //user.password comes from the database
            bcrypt.compare(password, user.password, (err, data) => {
                //if error than throw error
                if (err) throw err

                //if both match than you can do anything
                if (data) {
                    return res.status(200).json({ msg: "Login success" })
                } else {
                    return res.status(401).json({ msg: "Invalid credencial" })
                }

            })

        })

})

module.exports = router
xwbd5t1u

xwbd5t1u3#

如果您要在浏览器(HTML)中使用bcryptjs,则可以添加bcryptjs CDN来完成此操作。
内容分发网络-https://cdn.jsdelivr.net/npm/bcryptjs@2.4.3/dist/bcrypt.js
示例-
HTML-(在标签中的CDN上方添加)
联属萨摩亚-

var bcrypt = dcodeIO.bcrypt;

    /** One way, can't decrypt but can compare */
    var salt = bcrypt.genSaltSync(10);

    /** Encrypt password */
    bcrypt.hash('anypassword', salt, (err, res) => {
        console.log('hash', res)
        hash = res
        compare(hash)
    });

    /** Compare stored password with new encrypted password */
    function compare(encrypted) {
        bcrypt.compare('aboveusedpassword', encrypted, (err, res) => {
            // res == true or res == false
            console.log('Compared result', res, hash) 
        })
    }

如果要在Nodejs中执行相同操作

/**按如下方式导入库并使用与上面编写的函数相同的函数 */

var bcrypt = require('bcryptjs')
oaxa6hgo

oaxa6hgo4#

从我看来你的逻辑是正确的。
如果你使用的是mongoose,我建议你使用保存钩子。

用户架构

userSchema.pre('save', function(next) {
  // only hash the password if it has been modified (or is new)
  if (!this.isModified('password')) {
    return next();
  }
  // generate a salt
  return bcrypt.genSalt(10, function(error, salt) {
    if (error) {
      return next(error);
    }

  // hash the password using the new salt
    return bcrypt.hash(this.password, salt, function(error, hash) {
      if (error) {
        return next(error);
      }
      // override the cleartext password with the hashed one
      this.password = hash;
      return next();
    });
  });
});

userSchema.methods.comparePassword = function(passw, cb) {
  bcrypt.compare(passw, this.password, function(err, isMatch) {
    if (err) {
      return cb(err, false);
    }
    return cb(null, isMatch);
  });
};

在您的路线中:

登录

...
return user.comparePassword(password, function(error, isMatch) {
  var payload = {
  iat: Math.round(Date.now() / 1000),
  exp: Math.round((Date.now() / 1000) + 30 * 24 * 60),
  iss: 'Whatever the issuer is example: localhost:3000',
  email: user.email
  };

  var token = jwt.encode(payload, 'secret');
  if (isMatch && !error) {
    // if user is found and password is right create a token
    return res.json({
      success: true,
      token: `JWT ${token}`,
      user: user,
      msg: 'Authentication was succesful'
      });
    }
    return next({code: 401, msg: 'Password is incorrect'});
  });
});

创建用户

// Pre hook will take care of password creation
return user.save()
.then(function(user) {
  var payload = {
  iat: Math.round(Date.now() / 1000),
  exp: Math.round((Date.now() / 1000) + 30 * 24 * 60),
  iss: 'Whatever the issuer is example: localhost:3000',
  email: user.email
  };

  var token = jwt.encode(payload, 'secret');
  return res.status(201).json({user, token: `JWT ${token}`, msg: 'User was succesfully created'});
})
.catch((err) => next(err));
bmvo0sr5

bmvo0sr55#

bcrypt.compare(req.body.password, user.password, function(err, results){
                if(err){
                    throw new Error(err)
                 }
                 if (results) {
                    return res.status(200).json({ msg: "Login success" })
                } else {
                    return res.status(401).json({ msg: "Invalid credencial" })
                }
               })
mlnl4t2r

mlnl4t2r6#

const bcrypt = require("bcryptjs");
const salt = bcrypt.genSaltSync(10);

const hashPassword = (password) => bcrypt.hashSync(password, salt);
const comparePassword = (password, hashedPassword) =>
  bcrypt.compareSync(password, hashedPassword);

相关问题