在 KrakenJS 中,如何在另一个中间件之前声明 Passport 中间件?

In KrakenJS, how to declare the Passport middleware before another one?

我在我的 Kraken 项目中使用 Passport 进行身份验证。 当我调用 authenticate 时,我传递了 "failWithError: true" 因此一个错误被传递到 "next" 回调。然后我在 config.json:

中有一个这样声明的 errorHandler 中间件
"errorHandler": {
    "priority": 130,
    "module": "path:./lib/errorHandler"
}

我的问题是passportreturns直接报错,估计是优先级的问题

我试过这样注册护照:

app.requestBeforeRoute = function requestBeforeRoute(server) {
    server.use(passport.initialize());
};
passport.use(auth.localApiKeyStrategy());

像这样:

app.on('middleware:before:errorHandler', function (eventargs) {
    passport.use(auth.localApiKeyStrategy());
    app.use(passport.initialize());
});

但它不起作用。 另外,我发现了这个:Adding a way to configure a scope to factory function 但我还不知道如何让它发挥作用。

非常感谢。

所以,最后我想出了一个解决方案。在我的例子中,我不需要来自 passport 的会话中间件,因为我正在开发一个 REST API.

首先,config.json中的护照声明:

"passport": {
    "enabled": true,
    "priority": 10,
    "module": {
        "name": "passport",
        "method": "initialize"
    }
}

然后在index.js,我说通行证使用我的策略:

passport.use(auth.localApiKeyStrategy());

最后,在模型的控制器中,我实现了自定义回调,正如 Passport 文档所说的那样,我位于 auth.js

router.get('/', function(req, res, next) {
    auth.authenticate(req, res, next, function() {
        // authenticated
        // stuff to do when authenticated
    });
});

// auth.js
exports.authenticate = function(req, res, next, callback) {
    passport.authenticate('localapikey', function(err, device) {
        if (err) {
            return next(err);
        }
        if (!device) {
            err = new Error();
            err.code = statusWell.UNAUTHORIZED;
            return next(err);
        }
        callback();
    })(req, res, next);
};

现在我可以处理身份验证并稍后使用下一个函数将错误传递给我的 errorHandler 中间件。