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

发布于 2024-11-06 18:31:39 字数 684 浏览 3 评论 0原文

我正在尝试使用 NodeJS 编写一个 REST-API 服务器,就像 Joyent 使用的服务器一样,一切都很好,除了我无法验证普通用户的身份验证。如果我跳转到终端并执行 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");

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

I'm trying to write a REST-API server with NodeJS like the one used by Joyent, and everything is ok except I can't verify a normal user's authentication. If I jump to a terminal and do curl -u username:password localhost:8000 -X GET, I can't get the values username:password on the NodeJS http server. If my NodeJS http server is something like

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");

, shouldn't I get the values username:password somewhere in the req object that comes from the callback ?
How can I get those values without having to use Connect's basic http auth ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

丘比特射中我 2024-11-13 18:31:39

用户名:密码作为 Base64 编码字符串包含在授权标头中。

试试这个:

const http = require('http');
 
http.createServer(function (req, res) {
  var header = req.headers.authorization || '';       // get the auth header
  var token = header.split(/\s+/).pop() || '';        // and the encoded auth token
  var auth = Buffer.from(token, 'base64').toString(); // convert from base64
  var parts = auth.split(/:/);                        // split on colon
  var username = parts.shift();                       // username is first
  var password = parts.join(':');                     // everything else is the password
 
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('username is "' + username + '" and password is "' + password + '"');
}).listen(1337, '127.0.0.1');

来自 HTTP 身份验证:基本和摘要式访问身份验证 - 第 2 部分基本身份验证方案(第 4-5 页) )

巴科斯-诺尔形式的基本身份验证

basic-credentials = base64-user-pass
base64-user-pass  = <base64 [4] encoding of user-pass,
                    except not limited to 76 char/line>
user-pass   = userid ":" password
userid      = *<TEXT excluding ":">
password    = *TEXT

The username:password is contained in the Authorization header as a base64-encoded string.

Try this:

const http = require('http');
 
http.createServer(function (req, res) {
  var header = req.headers.authorization || '';       // get the auth header
  var token = header.split(/\s+/).pop() || '';        // and the encoded auth token
  var auth = Buffer.from(token, 'base64').toString(); // convert from base64
  var parts = auth.split(/:/);                        // split on colon
  var username = parts.shift();                       // username is first
  var password = parts.join(':');                     // everything else is the password
 
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('username is "' + username + '" and password is "' + password + '"');
}).listen(1337, '127.0.0.1');

From HTTP Authentication: Basic and Digest Access Authentication - Part 2 Basic Authentication Scheme (Pages 4-5)

Basic Authentication in Backus-Naur Form

basic-credentials = base64-user-pass
base64-user-pass  = <base64 [4] encoding of user-pass,
                    except not limited to 76 char/line>
user-pass   = userid ":" password
userid      = *<TEXT excluding ":">
password    = *TEXT
佞臣 2024-11-13 18:31:39

如果您使用的是 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);

If you're using express, you can use the connect plugin (included with 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);
娇纵 2024-11-13 18:31:39

您可以使用 node-http-digest 进行基本身份验证或 everyauth,如果您的路线图中包含从外部服务添加授权。

You can use node-http-digest for basic auth or everyauth, if adding authorization from external services are in you roadmap.

送君千里 2024-11-13 18:31:39

我将此代码用于我自己的带有身份验证的入门网站。

它做了几件事:

  • 基本身份验证
  • 为/路由返回index.html
  • 时的错误
  • 允许端口参数
  • 提供内容而不会崩溃并静默处理运行最少量日志记录

在使用代码之前,npm installexpress

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);
});

I use this code for my own starter sites with auth.

It does several things:

  • basic auth
  • return index.html for / route
  • serve content without crashing and silent handle the error
  • allow port parameter when running
  • minimal amount of logging

Before using the code, 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);
});
独自唱情﹋歌 2024-11-13 18:31:39

它可以在纯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');

It can be implemented easily in pure node.js with no dependency, this is my version which is based on this answer for express.js but simplified so you can see the basic idea easily:

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');
待"谢繁草 2024-11-13 18:31:39

Restify 框架 (http://mcavage.github.com/node-restify/) 包括用于“基本”和“签名”身份验证方案的授权标头解析器。

The restify framework (http://mcavage.github.com/node-restify/) includes an authorization header parser for "basic" and "signature" authentication schemes.

野生奥特曼 2024-11-13 18:31:39

您可以使用 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 ...
});

// Creating new HTTP server.
http.createServer(basic, function(req, res) {
    res.end("Welcome to private area - " + req.user + "!");
}).listen(1337);

You can use http-auth module

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

// Creating new HTTP server.
http.createServer(basic, function(req, res) {
    res.end("Welcome to private area - " + req.user + "!");
}).listen(1337);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文