Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add simple digest auth implementation #118

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
95 changes: 92 additions & 3 deletions lib/node/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -449,18 +449,102 @@ Request.prototype.redirect = function(res){
return this;
};

/**
* Compute an MD5 hash
*
* @param {String} str
*/

function md5(str) {
return require('crypto').createHash('md5').update(str).digest('hex');
}

/**
* Attempt to retry a request with authorization headers
*
* @param {IncomingMessage} res
* @return {Request} for chaining
* @api private
*/

Request.prototype.authorize = function(res) {
var authHeader = res.headers['www-authenticate']
, authVerb = authHeader.split(' ')[0];

delete this.req;

switch (authVerb) {
case 'Basic':
this.auth(this._user, this._pass, true);
break;

case 'Digest':
// TODO: More complete implementation of RFC 2617. For reference:
// http://tools.ietf.org/html/rfc2617#section-3
// https://github.com/bagder/curl/blob/master/lib/http_digest.c

var matches = authHeader.match(/([a-z0-9_-]+)="([^"]+)"/gi)
, url = parse(this.url)
, path = url.pathname + (url.query ? '?' + url.query : '')
, challenge = {};

for (var i = 0; i < matches.length; i++) {
var eqPos = matches[i].indexOf('=')
, key = matches[i].substring(0, eqPos)
, quotedValue = matches[i].substring(eqPos + 1);
challenge[key] = quotedValue.substring(1, quotedValue.length - 1);
}

var ha1 = md5(this._user + ':' + challenge.realm + ':' + this._pass)
, ha2 = md5(this.method + ':' + path)
, response = md5(ha1 + ':' + challenge.nonce + ':1::auth:' + ha2)
, authValues = {
username: this._user,
realm: challenge.realm,
nonce: challenge.nonce,
uri: path,
qop: challenge.qop,
response: response,
nc: 1,
cnonce: ''
};

authHeader = [];
for (var k in authValues) {
authHeader.push(k + '="' + authValues[k] + '"');
}
authHeader = 'Digest ' + authHeader.join(', ');
this.set('Authorization', authHeader);
this._sentAuth = true;

break;
}

this._data = null;
this.end(this._callback);
return this;
}

/**
* Set Authorization field value with `user` and `pass`.
*
* @param {String} user
* @param {String} pass
* @param {Boolean} sendImmediately whether to send Basic authorization with
* the first request (default true)
* @return {Request} for chaining
* @api public
*/

Request.prototype.auth = function(user, pass){
var str = new Buffer(user + ':' + pass).toString('base64');
return this.set('Authorization', 'Basic ' + str);
Request.prototype.auth = function(user, pass, sendImmediately){
this._user = user;
this._pass = pass;
if (sendImmediately || typeof sendImmediately == 'undefined') {
this._sentAuth = true;
var str = new Buffer(user + ':' + pass).toString('base64');
this.set('Authorization', 'Basic ' + str);
}
return this;
};

/**
Expand Down Expand Up @@ -620,6 +704,11 @@ Request.prototype.end = function(fn){
return self.redirect(res);
}

// unauthorized
if (res.statusCode == 401 && !self._sentAuth && self._user && self._pass) {
return self.authorize(res);
}

// zlib support
if (/^(deflate|gzip)$/.test(res.headers['content-encoding'])) {
utils.unzip(req, res);
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
},
"devDependencies": {
"express": "3.0.0rc5",
"http-auth": "1.2.2",
"should": "*",
"mocha": "*"
},
Expand Down
70 changes: 70 additions & 0 deletions test/node/digest-auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@

var EventEmitter = require('events').EventEmitter
, request = require('../../')
, express = require('express')
, assert = require('assert')
, app = express()
, auth = require('http-auth');

var digest = auth({
authRealm: 'Test digest realm',
authList: ['james:learnnode'],
authType: 'digest'
});

app.use(digest);

app.get('/', function(req, res){
res.end('you win!');
});

app.listen(3030);

describe('Digest auth', function(){
describe('when credentials are present in url', function(){
it('should use digest authentication', function(done){
request
.get('http://james:learnnode@localhost:3030')
.end(function(res){
res.status.should.equal(200);
done();
});
})
})

describe('req.auth(user, pass)', function(){
it('should use digest authentication', function(done){
request
.get('http://localhost:3030')
.auth('james', 'learnnode')
.end(function(res){
res.status.should.equal(200);
done();
});
})
})

describe('req.auth(user, pass, true)', function(){
it('should use digest authentication', function(done){
request
.get('http://localhost:3030')
.auth('james', 'learnnode', true)
.end(function(res){
res.status.should.equal(200);
done();
});
})
})

describe('req.auth(user, pass, false)', function(){
it('should use digest authentication', function(done){
request
.get('http://localhost:3030')
.auth('james', 'learnnode', false)
.end(function(res){
res.status.should.equal(200);
done();
});
})
})
})