4

我有这样的快速路线:

app.get('/', auth.authOrDie, function(req, res) {
    res.send();
});

其中authOrDie函数是这样定义的(在我的auth.js模块中):

exports.authOrDie = function(req, res, next) {
    if (req.isAuthenticated()) {
        return next();
    } else {
        res.send(403);
    }
});

现在,当用户未通过身份验证时,我想验证 http 请求是否具有 Authorization (Basic) 标头。为此,我想使用出色的连接中间件basicAuth()

如您所知,Express 建立在 Connect 之上,因此我可以使用express.basicAuth.

basicAuth通常这样使用:

app.get('/', express.basicAuth(function(username, password) {
    // username && password verification...
}), function(req, res) {
    res.send();
});

但是,我想在我的authOrDie函数中使用它:

exports.authOrDie = function(req, res, next) {
    if (req.isAuthenticated()) {
        return next();
    } else if {
        // express.basicAuth ??? ******
    } else {
        res.send(403);
    }
});

******如何使用良好的参数调用 basicAuth 函数(req ? res ? next ? ...)。

谢谢。

4

1 回答 1

8

调用该express.basicAuth函数会返回要调用的中间件函数,因此您可以像这样直接调用它:

exports.authOrDie = function(req, res, next) {
    if (req.isAuthenticated()) {
        return next();
    } else {
        return express.basicAuth(function(username, password) {
            // username && password verification...
        })(req, res, next);
    }
});
于 2013-01-10T22:03:17.477 回答