无法使用节点请求模块进行基本的HTTPvalidation
我正在使用mochatesting我的应用程序,我想testing一个HTTP响应头代码,这取决于我通过基本的HTTP身份validation发送给它的凭据。
在客户端,我做了这样的AJAX调用服务器:
$.ajax({ type: 'GET', url: url, beforeSend: function(xhr){ xhr.setRequestHeader("Authorization", "Basic " +btoa("username:password") ); }, success:function(rsp){ // do whatever I need; } });
它完美的作品。 它的凭据是错误的,那么该网站将回应智慧302
在我的testing文件( 摩卡 ),我尝试发送相同的请求,但由于某种原因,它不工作。
这是我尝试的不同方式:
it('should return 302 because wrong credentials', function(done){ var auth = "Basic " +new Buffer("username:password").toString('base64'); var options = { url: url, headers: { "Authorization": auth } }; request.get(options, function(err, res, body){ console.log(res.statusCode); assert.equal(302, res.statusCode); done(); }); }); ----------------------- it('should return 302 because wrong credentials', function(done){ request.get(url, { 'auth': { 'username':'username', 'password':'password' } }, function(err, res, body) { assert.equal(302, res.statusCode); done(); }); });
但是,无论如何,我得到一个HTTP 200响应代码。
所以为什么? 我该如何处理呢?
Ps:对于那些非常谨慎的人来说,客户是不能公开使用的,因此我允许自己把证书放在里面。
编辑:更确切地说,你会发现下面处理请求的服务器代码(NodeJS)
function checkAuth(req, result, next){ var header = req.headers['authorization']; // Ignore the preflight OPTION call if(header != undefined){ var tmp = header.split(/\s+/).pop(); var credentials = new Buffer(tmp, 'base64').toString(); var parts = credentials.split(/:/); var username = parts[0]; var password = parts[1]; bcrypt.compare(username, config.get.username, function(err, res){ if(res){ bcrypt.compare(password, config.get.password, function(err, res){ if(res){ next(); } else { return result.redirect('/'); } }); } else { return result.redirect('/'); } }); } else { return result.redirect('/'); } } app.get('/server', checkAuth, getData.getMessages);
getData.getMessage()
方法返回以下内容:
return result.status(200).json(res);
request
自动跟随redirect,所以你需要禁用followRedirect
读取3xx
响应。
var options = { url: url, followRedirect: false, headers: { "Authorization": auth } };
对于HTTP基本authentication,您也可以使用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);
- 如何在Node.js中重新使用由Play Framework 2.2设置的签名cookie?
- socket.io客户端名称空间授权
- Laravel 5:使用Laravel会话数据的Socket.io客户机authentication
- Cloud9 IDE上的Nodejs中的Redis:
- 错误:401(未授权),Passport身份validation在节点中
- 节点JS LDAPauthentication用户
- 使用nodejs web服务器validation用户,但没有框架
- NodeJS – 使用Active Directory进行身份validation
- 使用json文章的摘要authentication的curl命令