Skip to content

Commit

Permalink
feat: Support Instantiating OAuth2Client with Credentials (#1652)
Browse files Browse the repository at this point in the history
  • Loading branch information
danielbankhead committed Oct 2, 2023
1 parent ef29297 commit 4339d64
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 7 deletions.
14 changes: 8 additions & 6 deletions src/auth/oauth2client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -404,12 +404,6 @@ export interface VerifyIdTokenOptions {
maxExpiry?: number;
}

export interface OAuth2ClientOptions extends RefreshOptions {
clientId?: string;
clientSecret?: string;
redirectUri?: string;
}

export interface RefreshOptions {
// Eagerly refresh unexpired tokens when they are within this many
// milliseconds from expiring".
Expand All @@ -423,6 +417,13 @@ export interface RefreshOptions {
forceRefreshOnFailure?: boolean;
}

export interface OAuth2ClientOptions extends RefreshOptions {
clientId?: string;
clientSecret?: string;
redirectUri?: string;
credentials?: Credentials;
}

export class OAuth2Client extends AuthClient {
private redirectUri?: string;
private certificateCache: Certificates = {};
Expand Down Expand Up @@ -474,6 +475,7 @@ export class OAuth2Client extends AuthClient {
this.eagerRefreshThresholdMillis =
opts.eagerRefreshThresholdMillis || 5 * 60 * 1000;
this.forceRefreshOnFailure = !!opts.forceRefreshOnFailure;
this.credentials = opts.credentials || {};
}

protected static readonly GOOGLE_TOKEN_INFO_URL =
Expand Down
29 changes: 28 additions & 1 deletion test/test.oauth2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import * as path from 'path';
import * as qs from 'querystring';
import * as sinon from 'sinon';

import {CodeChallengeMethod, OAuth2Client} from '../src';
import {CodeChallengeMethod, Credentials, OAuth2Client} from '../src';
import {LoginTicket} from '../src/auth/loginticket';

nock.disableNetConnect();
Expand Down Expand Up @@ -1593,5 +1593,32 @@ describe('oauth2', () => {
/No access token is returned by the refreshHandler callback./
);
});

it('should accept and attempt to use an `access_token`', async () => {
const credentials: Credentials = {access_token: 'my-access-token'};
const url = 'http://example.com';

const client = new OAuth2Client({credentials});

const scope = nock(url, {
reqheaders: {
Authorization: `Bearer ${credentials.access_token}`,
},
})
.get('/')
.reply(200);

// We want the credentials object to be reference equal
assert.strict.equal(client.credentials, credentials);

await client.request({url});

scope.done();

// The access token should still be available after use
assert.strict.deepEqual(await client.getAccessToken(), {
token: credentials.access_token,
});
});
});
});

0 comments on commit 4339d64

Please sign in to comment.