javascript Node.js http 基本身份验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7343354/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 23:47:25  来源:igfitidea点击:

Node.js http basic auth

javascriptauthenticationubuntunode.jsbasic-authentication

提问by Jaime

Is it possible to do basic auth in Node.js just like in Apache?

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

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

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

I know that if using Express or Connect I can add middle-ware functionality and do user verification, but I'm trying to restrict the whole area (I don't need to authenticate users from a database just a couple of defined users) - I'm using Ubuntu.

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

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

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

That's something I can do, but I'm not sure if "exposing" or directly writing the user and password in the code is secure enough.

这是我可以做的事情,但我不确定“公开”或直接在代码中写入用户和密码是否足够安全。

Many thanks.

非常感谢。

回答by TWright

Passportprovides a clean mechanism to implement basic auth. I use it in my Node.js Express app to protect both my Angularjs-based UI as well as my RESTful API. To get passport up and running in your app do the following:

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

  • npm install passport

  • npm install passport-http (contains "BasicStrategy" object for basic auth)

  • Open up your app.js and add the following:

    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);
    
  • npm 安装通行证

  • npm installpassport-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);
    

回答by Vidal Graupera

Put this

把这个

app.use(express.basicAuth(function(user, pass) {
  return user === 'test' && pass === 'test';
}));

before the line to

前行

app.use(app.router);

to protect all routes with http basic auth

使用 http 基本身份验证保护所有路由

回答by gevorg

I think good choice could be http-authmodule

我认为不错的选择可能是http-auth模块

// Authentication module.
var auth = require('http-auth');
var basic = auth.basic({
    realm: "Simon Area.",
    file: __dirname + "/../data/users.htpasswd" // gevorg:gpass, Sarah:testpass ...
});

// Application setup.
var app = express();
app.use(auth.connect(basic));

// Setup route.
app.get('/', function(req, res){
  res.send("Hello from express - " + req.user + "!");
});

回答by Matthias

Have a look at: user authentication libraries for node.js?

看看: node.js 的用户身份验证库?

It does not answer your question 100% - but maybe it helps.

它不能 100% 回答您的问题 - 但也许会有所帮助。