护照 – dynamic覆盖策略

我有一个护照库的节点应用程序。 我使用这样的护照策略:

passport.use(someStrategy) 

以后可以dynamic地覆盖该策略吗? 在应用程序运行期间,我想在某个时候使用不同的策略。 实际上是一样的策略,但configuration不同。

如果我只是做另一个passport.use(someOtherStrategy),那么是不是只是添加另一个“中间件”护照? 那么这不会删除旧的,只需添加一个。 我想要删除旧的。 所以要么覆盖,要么删除并添加一个新的。

可以在护照中configuration多个命名的策略,即使是相同的types也是如此。 下面我可以有两个不同configuration的myStrategy实例,但名称不同,

例如:

 passport.use('someStrategy', new myStrategy(options)) passport.use('anotherStrategy', new myStrategy(differentOptions)); 

之后,在进行身份validation时,您可以指定要使用的策略:

 passport.authenticate('someStrategy', ...); 

使用上述方法,您可以configuration多个策略,并根据条件决定使用哪个策略:

 if (condition){ passport.authenticate('someStrategy', ...); } else{ passport.authenticate('anotherStrategy', ...); } 

要么:

 let strategyToUse = determineStrategy(); //dynamically choose which strategy you want passport.authenticate(strategyToUse, ...); 

从中间件堆栈中删除策略是有点棘手,没有内置的function,我不这样认为。 这可能涉及手动将策略拼接到堆栈之外。 这个问题可能会帮助你从堆栈中删除中间件。 其针对的expression/连接因此也应该在一定程度上适用于护照。

在护照源代码挖掘透露,重写可以轻松完成。 这里是代码的相关部分:

 Authenticator.prototype.use = function(name, strategy) { if (!strategy) { strategy = name; name = strategy.name; } if (!name) { throw new Error('Authentication strategies must have a name'); } this._strategies[name] = strategy; return this; }; ... ... Authenticator.prototype.unuse = function(name) { delete this._strategies[name]; return this; }; 

从代码中可以看出,如果您使用的策略在_strategies列表中有另一个策略已经使用的名称,那么它将被新的策略取代。 也可以用方法unuse删除策略,如代码中所见。

@Mitch你的答案是有益的,但是很less有话题。 可能有一部分是因为我不是很清楚,我正在寻找一种方法来覆盖现有的策略,而不仅仅是如何configuration多个策略。 对不起,在我的问题描述中,我不是很清楚。