在API上使用哈希密码对护照进行简单身份验证

时间:2018-07-13 00:30:23

标签: node.js express passport.js

我尝试使用护照在/ login路径上进行身份验证,给出一封电子邮件和一个密码(已经存储在数据库中-email +带有bcrypt的哈希密码)。但是,当我尝试进行身份验证时,我的代码永远不会进入passport.use ...

const passport = require("passport");
const LocalStrategy = require("passport-local").Strategy;

const db = require("../config/database");

/* Route methods */
exports.login = (req, res) => {
  const email = req.body.email;
  const password = req.body.password;
  console.log("It will be displayed");

  passport.use(
    new LocalStrategy(function(email, password, done) {
      console.log("It won't");
      db.User.findOne({ email: email }, function(err, user) {
        if (err) {
          return done(err);
        }
        if (!user) {
          return done(null, false, { message: "Incorrect email." });
        }

        if (!bcrypt.compareSync(password, user.dataValues.password)) {
          return done(null, false, { message: "Incorrect password." });
        }
        return done(null, user);
      });
    })
  );
};

此外,我创建了一个API,我想知道如何使用REST API对某人(带有会话)进行身份验证。我是否必须在端点上发送电子邮件和密码,然后创建会话?谢谢您的资源。

1 个答案:

答案 0 :(得分:0)

之所以会发生这种情况,是因为您只声明了实际的Strategy,但是您需要创建一条单独的路由,在其中使用passport.authenticate的本地策略对用户进行身份验证。

看看我创建的示例应用程序:https://github.com/BCooperA/express-authentication-starter-api

config/passport.js中,我创建了实际的Strategy

const passport         = require('passport')
    , mongoose         = require('mongoose')
    , User             = mongoose.model('User')
    , LocalStrategy    = require('passport-local').Strategy;

/**
 |--------------------------------------------------------------------------
 | Local authentication strategy (email, password)
 |--------------------------------------------------------------------------
 */
passport.use(new LocalStrategy({ usernameField: 'user[email]', passwordField: 'user[password]' },
    function(email, password, done) {
        User.findOne({email: email}, function (err, user) {
            if(err)
                return done(err);

            // incorrect credentials
            if (!user || !user.validPassword(password) || user.password === '') {
                return done(null, false, { errors: [{ msg: "Incorrect credentials" }] });
            }

            // inactive account
            if(user.activation_token !== '' || user.active === 0) {
                // account is not activated
                return done(null, false, { errors: [{ msg: "Inactive account" }] });
            }

            // all good
            return done(null, user);
        });
    }));

此外,我还创建了一个单独的POST路由,用于在使用passport.authenticate的本地登录用户。

routes/auth.routes.js中:

const router          = require('express').Router()
    , mongoose        = require('mongoose')
    , User            = mongoose.model('User')
    , passport        = require('passport');

/**
 |--------------------------------------------------------------------------
 | Local Authentication
 |--------------------------------------------------------------------------
 | Authenticates user using Local Strategy by Passport
 */
router.post('/signin', function(req, res, next) {

    if(req.body.user.email === '' || req.body.user.password === '')
    // overrides passports own error handler
        return res.status(422).json({errors: [{ msg: 'Missing credentials'}]});

    passport.authenticate('local', { session: false }, function(err, user, info) {
        if(err)
            return next(err);

        if(user) {
            // generate JSON web token to user
            user.token = user.generateJWT();

            // return user object
            return res.status(200).json({ user: user.toAuthJSON() });
        } else {
            // return any errors
            return res.status(422).json(info);
        }
    })(req, res, next);
});

module.exports = router;