这是一个经典的"没坏就别修"的故事
我已经使用Node.js创建了一个相对简单的HTTP请求处理程序。我通过将请求体的SHA-1与作为请求头的签名相匹配来验证请求:var http = require('http');
var crypto = require('crypto');
var secret = process.env.MY_SECRET;
var requestListener = function(req, res) {
if (req.method === 'POST') {
var body = '';
req.on('data', function(data) {
body += data;
});
req.on('end', function() {
var signature = req.headers['x-signature'];
var hash = crypto.createHmac('sha1', secret)
.update(body)
.digest('hex')
.toUpperCase();
if (signature === hash) {
// request is authorized
}
});
}
};
var server = http.createServer(requestListener);
server.listen(3000);
这工作得很好,除了一切都是丑陋的,还有Express.js的其他特性我想实现。我将代码重写如下:
var crypto = require('crypto');
var express = require('express');
var app = express();
var secret = process.env.MY_SECRET;
app.use(function(req, res, next) {
var signature = req.get('x-signature');
var hash = crypto.createHmac('sha1', secret)
.update(req.body)
.digest('hex')
.toUpperCase();
if (signature === hash) {
next();
} else {
// unauthorized
}
});
app.post('/', function(req, res) {
// request is authorized
});
app.listen(3000);
当然,加密方法不会运行,因为req.body
现在既不是字符串也不是缓冲区。但我该如何解决这个问题呢?
我包含了一些中间件:
app.use(bodyParser.json());
然后使用JSON.stringify
将结果in转换为字符串。这允许加密方法运行,但是哈希值和签名不匹配!
是否有可能,快递正在做其他的请求体时,使用中间件,如身体解析器?这对我来说没有任何意义,但也许我错过了一些东西。
带body解析器
var options = {
inflate: true,
limit: '100kb',
type: 'application/octet-stream'
};
app.use(bodyParser.raw(options));
那么你可以使用
app.post(routeName, (req, res) => {
let body = '';
req.on('data', (data) => {
body += data;
console.log(data)
});
req.on('end', () => {
fs.appendFile(`./${fileName}.log`, 'n' + body, (err) => {
if (err) throw err;
});
});
res.end();
})
找到解决方案了。我刚刚创建了一个自定义的正文解析器。
function(req, res, next) {
req.setEncoding('utf8');
req.rawBody = '';
req.on('data', function(chunk) {
req.rawBody += chunk;
});
req.on('end', function(){
next();
});
}
我仍然不明白为什么bodyParser.text()不以同样的方式工作!
您在POST请求的正文中发送了什么?
我用你的算法签名了这个字符串:nodejs
,结果是:92FCFCFBCDB06B40F76FEE4E6271EFC2554290FD
然后我使用curl:
curl --header "x-signature: 92FCFCFBCDB06B40F76FEE4E6271EFC2554290FD" --data "something=nodejs" http://localhost:4040
这是我的服务器文件:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var secret = 'something';
var crypto = require('crypto');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(function(req, res, next) {
var signature = req.get('x-signature');
var hash = crypto
.createHmac('sha1', secret)
.update(req.body.something)
.digest('hex')
.toUpperCase();
if (signature === hash) {
next();
} else {
res.send('you do not have permission');
}
});
app.post('/', function(req, res) {
res.send('hey');
});
app.listen(4040, function() {
console.log('server up and running at 4040 port');
});
如果签名无效,您将看到一条消息说:you do not have permission
,但如果您发送有效签名,您将能够使用POST路由/
。