Javascript 从passport访问passport策略

Javascript 从passport访问passport策略,javascript,passport.js,Javascript,Passport.js,我使用passport和passport saml策略。在策略上,我想使用一个函数。我知道策略是这样使用的: const SamlStrategy = require('passport-saml').Strategy; passport.use(new SamlStrategy( {//options here...}, ...); 现在,我如何从passport变量访问策略(及其函数)?类似于passport.Strategy.functionIWantToCall()?您可

我使用passport和passport saml策略。在策略上,我想使用一个函数。我知道策略是这样使用的:

const SamlStrategy = require('passport-saml').Strategy;

   passport.use(new SamlStrategy(
   {//options here...}, ...);

现在,我如何从
passport
变量访问策略(及其函数)?类似于
passport.Strategy.functionIWantToCall()

您可以使用
passport按名称检索策略对象。\u Strategy(name)
,并通过
验证该对象上的函数:

var strategy = passport._strategy('saml');
var func     = strategy._verify;
但是,请注意,所有这些访问器都以下划线作为前缀,这意味着它们应该被视为私有的(它们没有文档记录,我在源代码中找到了它们)。它们不应该像这样被访问,只能通过内部Passport访问

更好的解决方案是创建一个单独的模块来封装策略对象:

// my-strategy.js
module.exports = new SamlStrategy(...);

// In your Passport setup:
...
passport.use(require('./my-strategy')));
...

// And elsewhere where you need to access the strategy:
var strategy = require('./my-strategy');
解决了这个问题

export class AuthController {
    constructor(private readonly samlStrategy: SamlStrategy) {
    }
    public logout(@Req() req, @Res() res) {     
       // Work around
       (this.samlStrategy as any).logout(req, function (err, req) {
            if (!err) {
                res.send('<h1>Logout Failure!!</h1>');
            }
        });
    }
}
导出类AuthController{
构造函数(私有只读samlStrategy:samlStrategy){
}
公共注销(@Req()Req,@Res()Res){
//变通
(此.samlStrategy与任何策略一样)。注销(请求,函数(错误,请求){
如果(!err){
res.send('Logout Failure!!');
}
});
}
}

但我想从策略中使用名为logout的函数,而不是verify。查看passport saml的源代码,我看到该策略有一个原型函数:strategy.prototype.logout=function(req,callback){this.\u saml.getLogoutUrl(req,callback);};是的,但那似乎没什么作用。它不会触发注销saml请求等,网络显示为空=/。它不调用Strategy.prototype.logout()。我看到有人这样做注销:,所以我认为它可以这样工作嗯,你是对的,它不调用任何策略注销处理程序。我将进一步研究它。@VillemiekOja
req.logout()
可能不是正确的方法。我编辑了我的答案,以展示如何存储对策略的引用,以便您可以使用GitHub PR中提到的
strategy.logout()
。非常感谢您的帮助!