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

feat: fetch-Compatible API #1939

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
151 changes: 62 additions & 89 deletions .readme-partials.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -40,18 +40,13 @@ body: |-
* Instead of specifying the type of client you'd like to use (JWT, OAuth2, etc)
* this library will automatically choose the right client based on the environment.
*/
async function main() {
const auth = new GoogleAuth({
scopes: 'https://www.googleapis.com/auth/cloud-platform'
});
const client = await auth.getClient();
const projectId = await auth.getProjectId();
const url = `https://dns.googleapis.com/dns/v1/projects/${projectId}`;
const res = await client.request({ url });
console.log(res.data);
}

main().catch(console.error);
const auth = new GoogleAuth({
scopes: 'https://www.googleapis.com/auth/cloud-platform'
});
const projectId = await auth.getProjectId();
const url = `https://dns.googleapis.com/dns/v1/projects/${projectId}`;
const res = await auth.fetch(url);
console.log(res.data);
```

## OAuth2
Expand Down Expand Up @@ -81,10 +76,11 @@ body: |-
*/
async function main() {
const oAuth2Client = await getAuthenticatedClient();
// Make a simple request to the People API using our pre-authenticated client. The `request()` method
// takes an GaxiosOptions object. Visit https://github.com/JustinBeckwith/gaxios.
// Make a simple request to the People API using our pre-authenticated client. The `fetch` and
// `request` methods accept a [`GaxiosOptions`](https://github.com/googleapis/gaxios)
// object.
const url = 'https://people.googleapis.com/v1/people/me?personFields=names';
const res = await oAuth2Client.request({url});
const res = await oAuth2Client.fetch(url);
console.log(res.data);

// After acquiring an access_token, you may want to check on the audience, expiration,
Expand Down Expand Up @@ -156,6 +152,7 @@ body: |-
This library will automatically obtain an `access_token`, and automatically refresh the `access_token` if a `refresh_token` is present. The `refresh_token` is only returned on the [first authorization](https://github.com/googleapis/google-api-nodejs-client/issues/750#issuecomment-304521450), so if you want to make sure you store it safely. An easy way to make sure you always store the most recent tokens is to use the `tokens` event:

```js
const auth = new GoogleAuth();
const client = await auth.getClient();

client.on('tokens', (tokens) => {
Expand All @@ -166,9 +163,10 @@ body: |-
console.log(tokens.access_token);
});

const projectId = await auth.getProjectId();
const url = `https://dns.googleapis.com/dns/v1/projects/${projectId}`;
const res = await client.request({ url });
// The `tokens` event would now be raised if this was the first request
const res = await client.fetch(url);
```

#### Retrieve access token
Expand Down Expand Up @@ -241,18 +239,14 @@ body: |-
const {JWT} = require('google-auth-library');
const keys = require('./jwt.keys.json');

async function main() {
const client = new JWT({
email: keys.client_email,
key: keys.private_key,
scopes: ['https://www.googleapis.com/auth/cloud-platform'],
});
const url = `https://dns.googleapis.com/dns/v1/projects/${keys.project_id}`;
const res = await client.request({url});
console.log(res.data);
}

main().catch(console.error);
const client = new JWT({
email: keys.client_email,
key: keys.private_key,
scopes: ['https://www.googleapis.com/auth/cloud-platform'],
});
const url = `https://dns.googleapis.com/dns/v1/projects/${keys.project_id}`;
const res = await client.fetch(url);
console.log(res.data);
```

The parameters for the JWT auth client including how to use it with a `.pem` file are explained in [samples/jwt.js](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/jwt.js).
Expand Down Expand Up @@ -288,16 +282,12 @@ body: |-
}
const keys = JSON.parse(keysEnvVar);

async function main() {
// load the JWT or UserRefreshClient from the keys
const client = auth.fromJSON(keys);
client.scopes = ['https://www.googleapis.com/auth/cloud-platform'];
const url = `https://dns.googleapis.com/dns/v1/projects/${keys.project_id}`;
const res = await client.request({url});
console.log(res.data);
}

main().catch(console.error);
// load the JWT or UserRefreshClient from the keys
const client = auth.fromJSON(keys);
client.scopes = ['https://www.googleapis.com/auth/cloud-platform'];
const url = `https://dns.googleapis.com/dns/v1/projects/${keys.project_id}`;
const res = await client.fetch(url);
console.log(res.data);
```

**Important**: If you accept a credential configuration (credential JSON/File/Stream) from an external source for authentication to Google Cloud, you must validate it before providing it to any Google API or library. Providing an unvalidated credential configuration to Google APIs can compromise the security of your systems and data. For more information, refer to [Validate credential configurations from external sources](https://cloud.google.com/docs/authentication/external/externally-sourced-credentials).
Expand All @@ -313,18 +303,14 @@ body: |-
``` js
const {auth, Compute} = require('google-auth-library');

async function main() {
const client = new Compute({
// Specifying the service account email is optional.
serviceAccountEmail: '[email protected]'
});
const projectId = await auth.getProjectId();
const url = `https://dns.googleapis.com/dns/v1/projects/${projectId}`;
const res = await client.request({url});
console.log(res.data);
}

main().catch(console.error);
const client = new Compute({
// Specifying the service account email is optional.
serviceAccountEmail: '[email protected]'
});
const projectId = await auth.getProjectId();
const url = `https://dns.googleapis.com/dns/v1/projects/${projectId}`;
const res = await client.fetch(url);
console.log(res.data);
```

## Workload Identity Federation
Expand Down Expand Up @@ -1023,17 +1009,14 @@ body: |-
The library can now automatically choose the right type of client and initialize credentials from the context provided in the configuration file.

```js
async function main() {
const auth = new GoogleAuth({
scopes: 'https://www.googleapis.com/auth/cloud-platform'
});
const client = await auth.getClient();
const projectId = await auth.getProjectId();
// List all buckets in a project.
const url = `https://storage.googleapis.com/storage/v1/b?project=${projectId}`;
const res = await client.request({ url });
console.log(res.data);
}
const auth = new GoogleAuth({
scopes: 'https://www.googleapis.com/auth/cloud-platform'
});
const projectId = await auth.getProjectId();
// List all buckets in a project.
const url = `https://storage.googleapis.com/storage/v1/b?project=${projectId}`;
const res = await client.fetch(url);
console.log(res.data);
```

When using external identities with Application Default Credentials in Node.js, the `roles/browser` role needs to be granted to the service account.
Expand All @@ -1056,14 +1039,12 @@ body: |-
const {ExternalAccountClient} = require('google-auth-library');
const jsonConfig = require('/path/to/config.json');

async function main() {
const client = ExternalAccountClient.fromJSON(jsonConfig);
client.scopes = ['https://www.googleapis.com/auth/cloud-platform'];
// List all buckets in a project.
const url = `https://storage.googleapis.com/storage/v1/b?project=${projectId}`;
const res = await client.request({url});
console.log(res.data);
}
const client = ExternalAccountClient.fromJSON(jsonConfig);
client.scopes = ['https://www.googleapis.com/auth/cloud-platform'];
// List all buckets in a project.
const url = `https://storage.googleapis.com/storage/v1/b?project=${projectId}`;
const res = await client.fetch(url);
console.log(res.data);
```

#### Security Considerations
Expand All @@ -1087,15 +1068,11 @@ body: |-
// Make a request to a protected Cloud Run service.
const {GoogleAuth} = require('google-auth-library');

async function main() {
const url = 'https://cloud-run-1234-uc.a.run.app';
const auth = new GoogleAuth();
const client = await auth.getIdTokenClient(url);
const res = await client.request({url});
console.log(res.data);
}

main().catch(console.error);
const url = 'https://cloud-run-1234-uc.a.run.app';
const auth = new GoogleAuth();
const client = await auth.getIdTokenClient(url);
const res = await client.fetch(url);
console.log(res.data);
```

A complete example can be found in [`samples/idtokens-serverless.js`](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/idtokens-serverless.js).
Expand All @@ -1107,16 +1084,12 @@ body: |-
// Make a request to a protected Cloud Identity-Aware Proxy (IAP) resource
const {GoogleAuth} = require('google-auth-library');

async function main()
const targetAudience = 'iap-client-id';
const url = 'https://iap-url.com';
const auth = new GoogleAuth();
const client = await auth.getIdTokenClient(targetAudience);
const res = await client.request({url});
console.log(res.data);
}

main().catch(console.error);
const targetAudience = 'iap-client-id';
const url = 'https://iap-url.com';
const auth = new GoogleAuth();
const client = await auth.getIdTokenClient(targetAudience);
const res = await client.fetch(url);
console.log(res.data);
```

A complete example can be found in [`samples/idtokens-iap.js`](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/idtokens-iap.js).
Expand Down Expand Up @@ -1189,7 +1162,7 @@ body: |-

// Use impersonated credentials:
const url = 'https://www.googleapis.com/storage/v1/b?project=anotherProjectID'
const resp = await targetClient.request({ url });
const resp = await targetClient.fetch(url);
for (const bucket of resp.data.items) {
console.log(bucket.name);
}
Expand Down
Loading
Loading