Node.JS中的基本HTTP身份验证?

Joã*_*imo 45 authentication http basic-authentication node.js

我正在尝试使用类似于Joyent使用的NodeJS编写REST-API服务器,除了我无法验证普通用户的身份验证之外,一切正常.如果我跳到终端并且这样做curl -u username:password localhost:8000 -X GET,我就无法在NodeJS http服务器上获得值username:password.如果我的NodeJS http服务器是这样的

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(1337, "127.0.0.1");
Run Code Online (Sandbox Code Playgroud)

,我不应该在来自回调的req对象中获取值username:password 吗?如何在不使用Connect的基本http auth的情况下获取这些值?

Rob*_*sch 93

username:password 作为base64编码的字符串包含在Authorization标头.

试试这个:

http.createServer(function(req,res){
  var header=req.headers['authorization']||'',        // get the header
      token=header.split(/\s+/).pop()||'',            // and the encoded auth token
      auth=new Buffer.from(token, 'base64').toString(),    // convert from base64
      parts=auth.split(/:/),                          // split on colon
      username=parts[0],
      password=parts[1];

  res.writeHead(200,{'Content-Type':'text/plain'});
  res.end('username is "'+username+'" and password is "'+password+'"');

}).listen(1337,'127.0.0.1');
Run Code Online (Sandbox Code Playgroud)

有关http授权的详细信息,请访问http://www.ietf.org/rfc/rfc2617.txt

  • 示例中的第三行已经通过在空格上拆分标题来生成["Basic","abcdef0123456789"]并弹出最后一个值(即授权令牌). (4认同)
  • 不要忘记解析出"基本",即:'基本abcdef0123456789'=== req.headers.authorization (3认同)
  • 同意,但OP不希望这样做. (3认同)

Jer*_*oen 37

如果你使用express,你可以使用connect插件(包含在express中):

//Load express
var express = require('express');

//User validation
var auth = express.basicAuth(function(user, pass) {     
   return (user == "super" && pass == "secret");
},'Super duper secret area');

//Password protected area
app.get('/admin', auth, routes.admin);
Run Code Online (Sandbox Code Playgroud)

  • 从Express 4开始,我不相信这有效.请参阅http://stackoverflow.com/questions/24283848/express-basicauth-throwing-error?answertab=votes#tab-top或使用类似https://www.npmjs.org/package/http-auth的替代方案 (5认同)

Phi*_*lev 8

如果您在路线图中添加来自外部服务的授权,则可以将node-http-digest用于基本身份验证或Everyauth.


Gra*_* Li 6

我使用auth将此代码用于我自己的初创网站.

它做了几件事:

  • 基本认证
  • 返回index.html for/route
  • 提供内容而不会崩溃和静默处理错误
  • 运行时允许port参数
  • 最少的日志记录

在使用代码之前,npm install express

var express = require("express");
var app = express();

//User validation
var auth = express.basicAuth(function(user, pass) {     
     return (user == "username" && pass == "password") ? true : false;
},'dev area');

/* serves main page */
app.get("/", auth, function(req, res) {
try{
    res.sendfile('index.html')
}catch(e){}
});

/* add your other paths here */

/* serves all the static files */
app.get(/^(.+)$/, auth, function(req, res){ 
try{
    console.log('static file request : ' + req.params);
    res.sendfile( __dirname + req.params[0]); 
}catch(e){}
});

var port = process.env.PORT || 8080;
app.listen(port, function() {
    console.log("Listening on " + port);
});
Run Code Online (Sandbox Code Playgroud)


Ebr*_*owi 5

它可以在纯 Node.js 中轻松实现,无需依赖,这是我的版本,它基于Express.js 的此答案,但进行了简化,以便您可以轻松地看到基本思想:

const http = require('http');

http.createServer(function (req, res) {
    const userpass = Buffer.from(
        (req.headers.authorization || '').split(' ')[1] || '',
        'base64'
    ).toString();
    if (userpass !== 'username:password') {
        res.writeHead(401, { 'WWW-Authenticate': 'Basic realm="nope"' });
        res.end('HTTP Error 401 Unauthorized: Access is denied');
        return;
    }
    res.end('You are in! Yay!!');
}).listen(1337, '127.0.0.1');
Run Code Online (Sandbox Code Playgroud)