Skip to content

Commit

Permalink
feat: use X-Goog-Api-Key header (#719)
Browse files Browse the repository at this point in the history
  • Loading branch information
alexander-fenster authored and JustinBeckwith committed May 29, 2019
1 parent 3318bff commit 35471d0
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 10 deletions.
2 changes: 1 addition & 1 deletion package.json
Expand Up @@ -37,7 +37,7 @@
"@types/mocha": "^5.2.1",
"@types/mv": "^2.1.0",
"@types/ncp": "^2.0.1",
"@types/nock": "^10.0.0",
"@types/nock": "^10.0.3",
"@types/node": "^10.5.1",
"@types/semver": "^6.0.0",
"@types/sinon": "^7.0.0",
Expand Down
6 changes: 3 additions & 3 deletions src/auth/oauth2client.ts
Expand Up @@ -756,7 +756,7 @@ export class OAuth2Client extends AuthClient {
}

if (this.apiKey) {
return {headers: {}};
return {headers: {'X-Goog-Api-Key': this.apiKey}};
}
let r: GetTokenResponse | null = null;
let tokens: Credentials | null = null;
Expand Down Expand Up @@ -885,9 +885,9 @@ export class OAuth2Client extends AuthClient {
opts.headers = opts.headers || {};
opts.headers.Authorization = r.headers.Authorization;
}

if (this.apiKey) {
opts.params = Object.assign(opts.params || {}, {key: this.apiKey});
opts.headers = opts.headers || {};
opts.headers['X-Goog-Api-Key'] = this.apiKey;
}
r2 = await this.transporter.request<T>(opts);
} catch (e) {
Expand Down
17 changes: 11 additions & 6 deletions test/test.googleauth.ts
Expand Up @@ -242,9 +242,8 @@ describe('googleauth', () => {
it('should make a request with the api key', async () => {
const scope = nock(BASE_URL)
.post(ENDPOINT)
.query({key: API_KEY})
.reply(uri => {
assert(uri.indexOf('key=' + API_KEY) > -1);
.reply(function(uri) {
assert.strictEqual(this.req.headers['x-goog-api-key'][0], API_KEY);
return [200, RESPONSE_BODY];
});
const client = auth.fromAPIKey(API_KEY);
Expand All @@ -257,13 +256,19 @@ describe('googleauth', () => {
scope.done();
});

it('should put the api key in the headers', async () => {
const client = auth.fromAPIKey(API_KEY);
const headers = await client.getRequestHeaders();
assert.strictEqual(headers['X-Goog-Api-Key'], API_KEY);
});

it('should make a request while preserving original parameters', async () => {
const OTHER_QS_PARAM = {test: 'abc'};
const scope = nock(BASE_URL)
.post(ENDPOINT)
.query({test: OTHER_QS_PARAM.test, key: API_KEY})
.reply(uri => {
assert(uri.indexOf('key=' + API_KEY) > -1);
.query({test: OTHER_QS_PARAM.test})
.reply(function(uri) {
assert.strictEqual(this.req.headers['x-goog-api-key'][0], API_KEY);
assert(uri.indexOf('test=' + OTHER_QS_PARAM.test) > -1);
return [200, RESPONSE_BODY];
});
Expand Down

0 comments on commit 35471d0

Please sign in to comment.