在PassportJS中使用多种本地策略 [英] Use multiple local strategies in PassportJS

查看:391
本文介绍了在PassportJS中使用多种本地策略的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对PassportJS使用多种本地策略.我不尝试使用本地,facebook和gmail等. 我有两组用户存储在单独的对象中,并且我想使用本地策略对两者进行身份验证.就目前而言,我不能对两者使用相同的本地策略,因为它们具有不同的对象属性,这使我查询不同的对象.有什么办法吗?否则对此的任何建议将不胜感激.

I'm trying to use multiple LOCAL strategies with PassportJS. I'm not trying to use local, facebook, and gmail, etc. I have two sets of users stored in separate objects and I want to use a local strategy to authenticate both. As it stands, I cannot use the same local strategy for both because they have different object properties which has me querying different objects. Is there any way to do this? OR any suggestions around this would be greatly appreciated.

推荐答案

我认为这是不可能的,因为据我所知,您需要一种将请求移交给"第二种策略的方法一个失败了,我不认为那是可能的.

I don't think it's possible, because as far as I can see you need some method of 'handing off' a request to the second strategy when the first one fails, and I don't believe that's possible.

但是您也许可以使用一种本地策略,而只是尝试使用两种方法对传入的数据进行身份验证.

But you might be able to use one local strategy, and just try to authenticate the incoming data using both methods.

作为一个简单的示例(使用Mongoose作为示例数据库):

As a simple example (using Mongoose as an example database):

passport.use(new LocalStrategy(function(username, password, done) {
  Model1.findOne({ username : username }, function(err, user) {
    // first method succeeded?
    if (!err && user && passwordMatches(...)) {
      return done(null, user);
    }
    // no, try second method:
    Model2.findOne({ name : username }, function(err, user) {
      // second method succeeded?
      if (! err && user && passwordMatches(...)) {
        return done(null, user);
      }
      // fail! 
      done(new Error('invalid user or password'));
    });
  }); 
}));

对于序列化/反序列化,您可能需要在传递给doneuser对象中存储一些属性,以表示反序列化用户所需的模型.

For serialization/deserialization you might need to store some property in the user object that you pass to done to signify which model is required to deserialize the user.

这篇关于在PassportJS中使用多种本地策略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆