Added test for OAuth2Client#request retry, fixed implementation

This commit is contained in:
murgatroid99
2016-03-25 11:00:42 -07:00
parent 2b5ebfc85c
commit 3ce01ec28a
2 changed files with 40 additions and 2 deletions

View File

@@ -344,12 +344,17 @@ OAuth2Client.prototype.request = function(opts, callback) {
// Hook the callback routine to call the _postRequest method.
var postRequestCb = function(err, body, resp) {
// Automatically retry 401 and 403 responses
if (retry && err && (err.code == 401 || err.code == 403)) {
// if err is set, then getting credentials failed, and retrying won't help
if (retry && !err && resp &&
(resp.statusCode == 401 || resp.statusCode == 403)) {
/* It only makes sense to retry once, because the retry is intended to
* handle expiration-related failures. If refreshing the token does not
* fix the failure, then refreshing again probably won't help */
retry = false;
that.getRequestMetadata(unusedUri, authCb);
// Force token refresh
that.refreshAccessToken(function() {
that.getRequestMetadata(unusedUri, authCb);
});
} else {
that._postRequest(err, body, resp, callback);
}

View File

@@ -267,6 +267,39 @@ describe('JWT auth client', function() {
});
});
it('should refresh token if the server returns 403', function(done) {
var scope = nock('http://example.com')
.log(console.log)
.get('/access')
.reply(403);
var auth = new googleAuth();
var jwt = new auth.JWT(
'foo@serviceaccount.com',
'/path/to/key.pem',
null,
['http://example.com'],
'bar@subjectaccount.com');
jwt.credentials = {
access_token: 'woot',
refresh_token: 'jwt-placeholder',
expiry_date: (new Date()).getTime() + 5000
};
jwt.gtoken = {
getToken: function(callback) {
return callback(null, 'abc123');
}
};
jwt.request({ uri : 'http://example.com/access' }, function() {
assert.equal('abc123', jwt.credentials.access_token);
nock.cleanAll();
done();
});
});
it('should not refresh if not expired', function(done) {
var scope = nock('https://accounts.google.com')
.log(console.log)