如何在 Sails 中使用 http-auth

How to use http-auth with Sails

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

最简单的方法是什么?

看起来像 http-auth,文档解释了如何为 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();
        }

    }
};

原因

我认为您的问题来自此页面 http://sailsjs.org/documentation/concepts/middleware that uses incorrect pattern for http-auth 模块。

解决方案

SailsJS 使用 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-auth 的作者将连接功能移到了另一个名为 http-auth-connect 的包中,实现基本身份验证对我来说很有效。

但是,我面临一个问题,如何不硬编码用户名和密码,并以环境配置的形式使用它。

var httpAuth = require('http-auth');
var authConnect = require('http-auth-connect');

var basic = httpAuth.basic({
  realm: 'admin area'
}, function (username, password, onwards) {
  return onwards(username === "username" && password === "password");
});
module.export.policies = {

    ...

    'controllerpath/': [authConnect(basic)],

    ...

}