Node.JS 中的基本 HTTP 身份验证?
我正在尝试使用 NodeJS 编写一个 REST-API 服务器,就像 Joyent 所使用的那样,以及一切没问题,只是我无法验证普通用户的身份验证.如果我跳转到终端并执行 curl -u username:password localhost:8000 -X GET
,则无法在 NodeJS http 服务器上获取 username:password 值.如果我的 NodeJS http 服务器类似于
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
');
}).listen(1337, "127.0.0.1");
,我不应该在来自回调的 req 对象中的某处获取值 username:password 吗?如何在不必使用 Connect 的基本 http 身份验证 的情况下获取这些值?>
, 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 ?
username:password 包含在 Authorization 标头中作为 base64 编码的字符串.
The username:password is contained in the Authorization header as a base64-encoded string.
试试这个:
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)
Backus-Naur 形式的基本身份验证
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