无法使用Passport登录捕获401条件

时间:2017-08-29 09:28:20

标签: mongoose passport.js passport-local

我正在使用带有本地策略的PassportJS和本地护照 - 本地猫鼬。这是我的登录脚本:

// Configure Passport (server.js)
// ---------------------------------------------------------------
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
// ---------------------------------------------------------------

// POST to /login (authenticate.js)
// ---------------------------------------------------------------
router.post('/login', (req, res) => {
    // server-side validation
  const errors = {
    username: Validator.validateusername(req.body.username),
    password: Validator.validatepassword(req.body.password),
  };
  if (!isEmpty(errors)) return res.send(JSON.stringify({ error: errors }));

  passport.authenticate('local')(req, res, () => {
    // If logged in, we should have user info to send back
    if (req.user) {
      const userdata = JSON.stringify(req.user);
      const token = jwt.sign({
        username: req.user.username,
        firstName: req.user.firstName,
        lastName: req.user.lastName,
        email: req.user.email,
        img: req.user.img,
      }, process.env.JWT_SECRET);
      res.cookie('token', token);
      return res.send(userdata);
    }
    // Otherwise return an error
    return res.send(JSON.stringify({ error: 'There was an error logging in' }));
  });
});

除非出现登录错误,否则此工作正常。如果登录因任何原因(401或500)失败,此脚本不应返回There was an error logging in消息吗?相反,它只返回401 Unauthorized

此身份验证查找的架构是:

const { mongoose } = require('../config/dbconfig');

const Schema = mongoose.Schema;
const passportLocalMongoose = require('passport-local-mongoose');

const User = new Schema({
  username: {
        type: String,
        lowercase: true,
        required: true,
        unique: true,
    },
  password: {
        type: String,
        select: false,
        required: true,
    },
  firstName: {
        type: String,
        required: true,
    },
  lastName: {
        type: String,
        required: true,
    },
  email: {
        type: String,
        lowercase: true,
        required: true,
        unique: true,
    },
  img: {
        type: String,
    },
}, { timestamps: true });

User.plugin(passportLocalMongoose);

module.exports = mongoose.model('User', User);

1 个答案:

答案 0 :(得分:2)

你称这个策略有点不对劲。您应该将其用作中间件,或使用custom callback方式。你的是这些之间的混合 - 你称之为中间件的策略,但提供你自己的next middleware function。由于身份验证被称为中间件,但未提供failureRedirect选项,因此Passport将return 401 by defaultnext函数是called when successfully authenticated,在您的情况下,它不是下一个中间件而是回调函数。

要使用自定义回调,您应该像这样编写路由处理程序:

app.post('/login', (req, res, next) => {
  // ...
  passport.authenticate('local', (err, user, info) => {
    if (err) { return next(err); }
    if (user) {
      // ...
      req.login(user, (err) => {
        if (err) { return next(err); }
        return res.send(userdata);
      });
    } else {
      return res.status(401).send({ error: 'There was an error logging in' });
    }
  })(req, res, next);
});