我正在尝试使用 NodeJS 编写一个 REST-API 服务器,就像使用的那样Joyent http://api.no.de,一切都很好,除了我无法验证普通用户的身份验证。如果我跳到终端并执行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");
,我不应该在其中的某个位置获取值 username:passwordreq来自回调的对象?
我怎样才能获得这些值而无需使用Connect 的基本 http 身份验证 http://senchalabs.github.com/connect/middleware-basicAuth.html ?
用户名:密码包含在授权标头中作为 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');
From HTTP 身份验证:基本和摘要式访问身份验证 - 第 2 部分基本身份验证方案(第 4-5 页) http://www.ietf.org/rfc/rfc2617.txt
巴科斯-诺尔形式的基本身份验证
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)