diff --git a/lib/oauth2.js b/lib/oauth2.js index a27c84d..8ab4777 100644 --- a/lib/oauth2.js +++ b/lib/oauth2.js @@ -87,7 +87,19 @@ exports.OAuth2.prototype.getOAuthAccessToken= function(code, params, callback) { this._request("POST", this._getAccessTokenUrl(params), {}, null, function(error, data, response) { if( error ) callback(error); else { - var results= querystring.parse(data); + var results; + try { + // As of http://tools.ietf.org/html/draft-ietf-oauth-v2-07 + // responses should be in JSON + results= JSON.parse( data ); + } + catch(e) { + // .... However both Facebook + Github currently use rev05 of the spec + // and neither seem to specify a content-type correctly in their response headers :( + // clients of these services will suffer a *minor* performance cost of the exception + // being thrown + results= querystring.parse( data ); + } var access_token= results["access_token"]; var refresh_token= results["refresh_token"]; delete results["refresh_token"]; diff --git a/tests/oauth2.js b/tests/oauth2.js new file mode 100644 index 0000000..4b49a44 --- /dev/null +++ b/tests/oauth2.js @@ -0,0 +1,27 @@ +var vows = require('vows'), + assert = require('assert'), + OAuth2= require('../lib/oauth2').OAuth2; + +vows.describe('OAuth2').addBatch({ + 'When handling the access token response': { + topic: new OAuth2(), + 'we should correctly extract the token if received as form-data': function (oa) { + oa._request= function( method, url, fo, bar, callback) { + callback(null, "access_token=access&refresh_token=refresh"); + }; + oa.getOAuthAccessToken("", {}, function(error, access_token, refresh_token) { + assert.equal( access_token, "access"); + assert.equal( refresh_token, "refresh"); + }); + }, + 'we should correctly extract the token if received as a JSON literal': function (oa) { + oa._request= function( method, url, fo, bar, callback) { + callback(null, '{"access_token":"access","refresh_token":"refresh"}'); + }; + oa.getOAuthAccessToken("", {}, function(error, access_token, refresh_token) { + assert.equal( access_token, "access"); + assert.equal( refresh_token, "refresh"); + }); + } + } +}).export(module); \ No newline at end of file