Node.js 如何在sail中使用httpauth

Node.js 如何在sail中使用httpauth,node.js,express,sails.js,http-auth,Node.js,Express,Sails.js,Http Auth,我已经将我的Sails应用程序部署到PaaS,我希望有简单的密码保护,这样就没有人可以访问我的暂存服务器 最简单的方法是什么 看起来,该文档解释了如何实现ExpressJS,但对于SailsJS,我找不到app.use() 我试过的 在我的policies.js文件中 module.exports.policies = { // '*': true, '*': require('http-auth').basic({ realm: 'admin area' },

我已经将我的Sails应用程序部署到PaaS,我希望有简单的密码保护,这样就没有人可以访问我的暂存服务器

最简单的方法是什么

看起来,该文档解释了如何实现ExpressJS,但对于SailsJS,我找不到
app.use()

我试过的 在我的
policies.js
文件中

module.exports.policies = {

  // '*': true,
    '*': require('http-auth').basic({
      realm: 'admin area'
    }, function customAuthMethod (username, password, onwards) {
      return onwards(username === "Tina" && password === "Bullock");
    }),
这导致了

info: Starting app...

error: Cannot map invalid policy:  { realm: 'admin area',
  msg401: '401 Unauthorized',
  msg407: '407 Proxy authentication required',
  contentType: 'text/plain',
  users: [] }

而且看起来策略不能应用于视图,而只能应用于操作

我的做法是使用
config/http.js
文件。正在那里创建自定义中间件

这是我的
http.js
文件:

var basicAuth = require('basic-auth'),
    auth = function (req, res, next) {
        var user = basicAuth(req);
        if (user && user.name === "username" && user.pass === "password") return next();
        res.set('WWW-Authenticate', 'Basic realm=Authorization Required');
        return res.send(401);
    };

module.exports.http = {

    customMiddleware: function (app) {
        app.use('/protected', auth);
    },

    middleware: {

        order: [
            'startRequestTimer',
            'cookieParser',
            'session',
            // 'requestLogger',
            'bodyParser',
            'handleBodyParserError',
            'compress',
            'methodOverride',
            'poweredBy',
            '$custom',
            'router',
            'www',
            'favicon',
            '404',
            '500'
        ],

        requestLogger: function (req, res, next) {
            console.log("Requested :: ", req.method, req.url);
            console.log('=====================================');
            return next();
        }

    }
};
理由 我认为您的问题来自此页面,该页面使用了不正确的模块模式

解决方案 使用
connect
/
express
风格的中间件,因此您需要做的唯一一件事就是为其提供适当的中间件

// Authentication module.
var auth = require('http-auth');
var basic = auth.basic({
        realm: "Simon Area."
    }, function (username, password, callback) { // Custom authentication.
        callback(username === "Tina" && password === "Bullock");
    }
});

// Use proper middleware.
module.exports.policies = {
    '*': auth.connect(basic)
    ...
待办事项 有必要通知SailsJS团队,以便他们删除错误的样本

相关链接

刚刚意识到您正在使用http身份验证,我的示例显示了基本身份验证。。。但逻辑是一样的,它将工作将http身份验证以同样的方式也…工作!谢谢分享
/protected
是放置要保护的页面的文件夹吗?如果您觉得这个问题很有趣,感谢您投票支持它。/protected是一个将使用该中间件的路由。。。你可以把任何东西放到那条路线上。。。这只是一个例子。。。在实际的用例中,我已经在该路径上提供了静态文件(由apidoc生成的api文档),然后还向其中添加了此身份验证。如果您真的对使用感兴趣,请查看我的答案。很明显,SailsJS文档不正确,导致了您的问题。我只是,所以Sails团队更新了他们的文档。