修正needle在摘要认证时第二次请求仍返回401错误
不知理论上是否正确,但是解决问题了。原因是:needle在第一次收到需要验证信息时,确实是计算出验证信息并将authorization添加到headers里直接返回给服务器,这样服务器就能返回数据。当再次请求服务器时needle就没有往headers里添加authorization了。
处理方法:
needle.js
//添加全局变量authInfo,用来保存authorization
var authInfo = null;
Needle.prototype.send_request = function(count, method, uri, config, post_data, out, callback) {
......
//在发送请求前判断authInfo是否为null,不为null,则重新计算authorization并添加到headers里
if(authInfo){
//digest = function(header, user, pass, method, path)
var auth_header = auth.digest(authInfo, config.credentials[0], config.credentials[1], request_opts.method, request_opts.path);
if (auth_header) {
authInfo = auth_header
request_opts.headers['authorization'] = auth_header
}
}
var request = protocol.request(request_opts, function(resp) {
if (resp.statusCode == 401 && headers['www-authenticate'] && config.credentials) {
if (!config.headers['authorization']) { // only if authentication hasn't been sent
var auth_header = auth.header(headers['www-authenticate'], config.credentials, request_opts);
if (auth_header) {
config.headers['authorization'] = auth_header;
// 保存验证信息
authInfo = auth_header;
return self.send_request(count, method, uri, config, post_data, out, callback);
}
}
}
}
}
auth.js
digest.generate = function(header, user, pass, method, path) {
......
//取出旧的nc值
if(typeof challenge.nc === 'string'){
nc = +challenge.nc
}
......
}