Node.js http基本身份验证

Jai*_*ime 14 javascript authentication ubuntu basic-authentication node.js

是否可以像在Apache中一样在Node.js中执行基本身份验证?

http://doc.norang.ca/apache-basic-auth.html

我知道如果使用Express或Connect我可以添加中间件功能并进行用户验证,但我试图限制整个区域(我不需要从数据库中验证用户只是几个已定义的用户) - 我正在使用Ubuntu.

https://github.com/kaero/node-http-digest

这是我能做的,但我不确定"暴露"或直接在代码中写入用户和密码是否足够安全.

非常感谢.

TWr*_*ght 17

Passport提供了一种干净的机制来实现基本身份验证.我在我的Node.js Express应用程序中使用它来保护我的基于Angularjs的UI以及我的RESTful API.要在您的应用程序中启动并运行护照,请执行以下操作:

  • npm安装护照

  • npm install passport-http(包含基本身份验证的"BasicStrategy"对象)

  • 打开你的app.js并添加以下内容:

    var passport = require('passport')    
    var BasicStrategy = require('passport-http').BasicStrategy
    
    passport.use(new BasicStrategy(
      function(username, password, done) {
        if (username.valueOf() === 'yourusername' &&
          password.valueOf() === 'yourpassword')
          return done(null, true);
        else
          return done(null, false);
      }
    ));
    
    // Express-specific configuration section
    // *IMPORTANT*
    //   Note the order of WHERE passport is initialized
    //   in the configure section--it will throw an error
    //   if app.use(passport.initialize()) is called after
    //   app.use(app.router) 
    app.configure(function(){
      app.use(express.cookieParser());
      app.use(express.session({secret:'123abc',key:'express.sid'}));
      app.set('views', __dirname + '/views');
      app.set('view engine', 'jade');
      app.set('view options', {
        layout: false
      });
      app.use(express.bodyParser());
      app.use(express.methodOverride());
      app.use(express.static(__dirname + '/public'));
      app.use(passport.initialize());
      app.use(app.router);
      app.use(logger);
    });
    
    // Routes
    
    app.get('/', passport.authenticate('basic', { session: false }), routes.index);
    app.get('/partials/:name', routes.partials);
    
    // JSON API
    
    app.get('/api/posts', passport.authenticate('basic', { session: false }), api.posts);
    app.get('/api/post/:id', passport.authenticate('basic', { session: false }), api.post)
    // --Repeat for every API call you want to protect with basic auth--
    
    app.get('*', passport.authenticate('basic', { session: false }), routes.index);
    
    Run Code Online (Sandbox Code Playgroud)


Vid*_*era 12

把它

app.use(express.basicAuth(function(user, pass) {
  return user === 'test' && pass === 'test';
}));
Run Code Online (Sandbox Code Playgroud)

前行到

app.use(app.router);
Run Code Online (Sandbox Code Playgroud)

使用http basic auth保护所有路由