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
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)
我使用auth将此代码用于我自己的初创网站.
它做了几件事:
在使用代码之前,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)
它可以在纯 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)
| 归档时间: |
|
| 查看次数: |
60730 次 |
| 最近记录: |