Node.JS 中的基本 HTTP 身份验证?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5951552/
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
Basic HTTP authentication in Node.JS?
提问by Jo?o Pinto Jerónimo
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
我正在尝试使用 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");
, shouldn't I get the values username:password somewhere in the reqobject that comes from the callback ? How can I get those values without having to use Connect's basic http auth?
,我不应该在来自回调的req对象中的某处获取值 username:password吗?如何在不必使用Connect 的基本 http auth 的情况下获取这些值?
回答by Rob Raisch
The username:password is contained in the Authorization header as a base64-encoded string.
username:password作为 base64-encoded string包含在 Authorization 标头中。
Try this:
尝试这个:
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');
Detail on http authorization can be found at http://www.ietf.org/rfc/rfc2617.txt
有关 http 授权的详细信息,请访问 http://www.ietf.org/rfc/rfc2617.txt
回答by Jeroen
If you're using express, you can use the connect plugin (included with express):
如果您使用 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);
回答by Phillip Kovalev
You can use node-http-digestfor basic auth or everyauth, if adding authorization from external services are in you roadmap.
如果在您的路线图中添加来自外部服务的授权,您可以将node-http-digest用于基本身份验证或everyauth。
回答by Grant Li
I use this code for my own starter sites with auth.
我将此代码用于我自己的带有 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
- 基本认证
- 为 / 路由返回 index.html
- 在不崩溃的情况下提供内容并静默处理错误
- 运行时允许端口参数
- 最少的日志记录
Before using the code, npm install express
使用代码前,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);
});
回答by Dave Pacheco
The restify framework (http://mcavage.github.com/node-restify/) includes an authorization header parser for "basic" and "signature" authentication schemes.
restify 框架 (http://mcavage.github.com/node-restify/) 包括用于“基本”和“签名”身份验证方案的授权标头解析器。
回答by Ebrahim Byagowi
It can be implemented easily in pure node.js with no dependency, this is my version which is based on this answer for express.jsbut simplified so you can see the basic idea easily:
它可以在没有依赖的纯 node.js 中轻松实现,这是我的版本,它基于express.js 的这个答案,但经过简化,因此您可以轻松了解基本思想:
var http = require('http');
http.createServer(function (req, res) {
var userpass = new Buffer((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');
回答by gevorg
You can use 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 ...
});
// Creating new HTTP server.
http.createServer(basic, function(req, res) {
res.end("Welcome to private area - " + req.user + "!");
}).listen(1337);

