Skip to content

Commit 137883a

Browse files
authored
feat(samples): auth samples (#1444)
1 parent d8508cb commit 137883a

9 files changed

+583
-0
lines changed

README.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1187,10 +1187,15 @@ Samples are in the [`samples/`](https://github.com/googleapis/google-auth-librar
11871187
| Sample | Source Code | Try it |
11881188
| --------------------------- | --------------------------------- | ------ |
11891189
| Adc | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/adc.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/adc.js,samples/README.md) |
1190+
| Authenticate Explicit | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/authenticateExplicit.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/authenticateExplicit.js,samples/README.md) |
1191+
| Authenticate Implicit With Adc | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/authenticateImplicitWithAdc.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/authenticateImplicitWithAdc.js,samples/README.md) |
11901192
| Compute | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/compute.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/compute.js,samples/README.md) |
11911193
| Credentials | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/credentials.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/credentials.js,samples/README.md) |
11921194
| Downscopedclient | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/downscopedclient.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/downscopedclient.js,samples/README.md) |
11931195
| Headers | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/headers.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/headers.js,samples/README.md) |
1196+
| Id Token From Impersonated Credentials | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/idTokenFromImpersonatedCredentials.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/idTokenFromImpersonatedCredentials.js,samples/README.md) |
1197+
| Id Token From Metadata Server | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/idTokenFromMetadataServer.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/idTokenFromMetadataServer.js,samples/README.md) |
1198+
| Id Token From Service Account | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/idTokenFromServiceAccount.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/idTokenFromServiceAccount.js,samples/README.md) |
11941199
| ID Tokens for Identity-Aware Proxy (IAP) | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/idtokens-iap.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/idtokens-iap.js,samples/README.md) |
11951200
| ID Tokens for Serverless | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/idtokens-serverless.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/idtokens-serverless.js,samples/README.md) |
11961201
| Jwt | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/jwt.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/jwt.js,samples/README.md) |
@@ -1199,6 +1204,7 @@ Samples are in the [`samples/`](https://github.com/googleapis/google-auth-librar
11991204
| Oauth2-code Verifier | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/oauth2-codeVerifier.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/oauth2-codeVerifier.js,samples/README.md) |
12001205
| Oauth2 | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/oauth2.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/oauth2.js,samples/README.md) |
12011206
| Sign Blob | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/signBlob.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/signBlob.js,samples/README.md) |
1207+
| Verify Google Id Token | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/verifyGoogleIdToken.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/verifyGoogleIdToken.js,samples/README.md) |
12021208
| Verifying ID Tokens from Identity-Aware Proxy (IAP) | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/verifyIdToken-iap.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/verifyIdToken-iap.js,samples/README.md) |
12031209
| Verify Id Token | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/verifyIdToken.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/verifyIdToken.js,samples/README.md) |
12041210

samples/README.md

Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,15 @@ This is Google's officially supported [node.js](http://nodejs.org/) client libra
1313
* [Before you begin](#before-you-begin)
1414
* [Samples](#samples)
1515
* [Adc](#adc)
16+
* [Authenticate Explicit](#authenticate-explicit)
17+
* [Authenticate Implicit With Adc](#authenticate-implicit-with-adc)
1618
* [Compute](#compute)
1719
* [Credentials](#credentials)
1820
* [Downscopedclient](#downscopedclient)
1921
* [Headers](#headers)
22+
* [Id Token From Impersonated Credentials](#id-token-from-impersonated-credentials)
23+
* [Id Token From Metadata Server](#id-token-from-metadata-server)
24+
* [Id Token From Service Account](#id-token-from-service-account)
2025
* [ID Tokens for Identity-Aware Proxy (IAP)](#id-tokens-for-identity-aware-proxy-iap)
2126
* [ID Tokens for Serverless](#id-tokens-for-serverless)
2227
* [Jwt](#jwt)
@@ -25,6 +30,7 @@ This is Google's officially supported [node.js](http://nodejs.org/) client libra
2530
* [Oauth2-code Verifier](#oauth2-code-verifier)
2631
* [Oauth2](#oauth2)
2732
* [Sign Blob](#sign-blob)
33+
* [Verify Google Id Token](#verify-google-id-token)
2834
* [Verifying ID Tokens from Identity-Aware Proxy (IAP)](#verifying-id-tokens-from-identity-aware-proxy-iap)
2935
* [Verify Id Token](#verify-id-token)
3036

@@ -60,6 +66,40 @@ __Usage:__
6066

6167

6268

69+
### Authenticate Explicit
70+
71+
View the [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/authenticateExplicit.js).
72+
73+
[![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/authenticateExplicit.js,samples/README.md)
74+
75+
__Usage:__
76+
77+
78+
`node samples/authenticateExplicit.js`
79+
80+
81+
-----
82+
83+
84+
85+
86+
### Authenticate Implicit With Adc
87+
88+
View the [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/authenticateImplicitWithAdc.js).
89+
90+
[![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/authenticateImplicitWithAdc.js,samples/README.md)
91+
92+
__Usage:__
93+
94+
95+
`node samples/authenticateImplicitWithAdc.js`
96+
97+
98+
-----
99+
100+
101+
102+
63103
### Compute
64104

65105
View the [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/compute.js).
@@ -128,6 +168,57 @@ __Usage:__
128168

129169

130170

171+
### Id Token From Impersonated Credentials
172+
173+
View the [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/idTokenFromImpersonatedCredentials.js).
174+
175+
[![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/idTokenFromImpersonatedCredentials.js,samples/README.md)
176+
177+
__Usage:__
178+
179+
180+
`node samples/idTokenFromImpersonatedCredentials.js`
181+
182+
183+
-----
184+
185+
186+
187+
188+
### Id Token From Metadata Server
189+
190+
View the [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/idTokenFromMetadataServer.js).
191+
192+
[![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/idTokenFromMetadataServer.js,samples/README.md)
193+
194+
__Usage:__
195+
196+
197+
`node samples/idTokenFromMetadataServer.js`
198+
199+
200+
-----
201+
202+
203+
204+
205+
### Id Token From Service Account
206+
207+
View the [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/idTokenFromServiceAccount.js).
208+
209+
[![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/idTokenFromServiceAccount.js,samples/README.md)
210+
211+
__Usage:__
212+
213+
214+
`node samples/idTokenFromServiceAccount.js`
215+
216+
217+
-----
218+
219+
220+
221+
131222
### ID Tokens for Identity-Aware Proxy (IAP)
132223

133224
Requests an IAP-protected resource with an ID Token.
@@ -268,6 +359,23 @@ __Usage:__
268359

269360

270361

362+
### Verify Google Id Token
363+
364+
View the [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/verifyGoogleIdToken.js).
365+
366+
[![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/verifyGoogleIdToken.js,samples/README.md)
367+
368+
__Usage:__
369+
370+
371+
`node samples/verifyGoogleIdToken.js`
372+
373+
374+
-----
375+
376+
377+
378+
271379
### Verifying ID Tokens from Identity-Aware Proxy (IAP)
272380

273381
Verifying the signed token from the header of an IAP-protected resource.

samples/authenticateExplicit.js

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
// Copyright 2022 Google LLC
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
/**
16+
* Lists storage buckets by authenticating with ADC.
17+
*/
18+
function main() {
19+
// [START auth_cloud_explicit_adc]
20+
/**
21+
* TODO(developer):
22+
* 1. Set up ADC as described in https://cloud.google.com/docs/authentication/external/set-up-adc
23+
* 2. Make sure you have the necessary permission to list storage buckets "storage.buckets.list"
24+
*/
25+
26+
const {GoogleAuth} = require('google-auth-library');
27+
const {Storage} = require('@google-cloud/storage');
28+
29+
async function authenticateExplicit() {
30+
const googleAuth = new GoogleAuth({
31+
scopes: 'https://www.googleapis.com/auth/cloud-platform',
32+
});
33+
34+
// Construct the Google credentials object which obtains the default configuration from your
35+
// working environment.
36+
// googleAuth.getApplicationDefault() will give you ComputeEngineCredentials
37+
// if you are on a GCE (or other metadata server supported environments).
38+
const {credential, projectId} = await googleAuth.getApplicationDefault();
39+
// If you are authenticating to a Cloud API, you can let the library include the default scope,
40+
// https://www.googleapis.com/auth/cloud-platform, because IAM is used to provide fine-grained
41+
// permissions for Cloud.
42+
// If you need to provide a scope, specify it as follows:
43+
// const googleAuth = new GoogleAuth({ scopes: scope });
44+
// For more information on scopes to use,
45+
// see: https://developers.google.com/identity/protocols/oauth2/scopes
46+
47+
const storageOptions = {
48+
projectId,
49+
authClient: credential,
50+
};
51+
52+
// Construct the Storage client.
53+
const storage = new Storage(storageOptions);
54+
const [buckets] = await storage.getBuckets();
55+
console.log('Buckets:');
56+
57+
for (const bucket of buckets) {
58+
console.log(`- ${bucket.name}`);
59+
}
60+
61+
console.log('Listed all storage buckets.');
62+
}
63+
64+
authenticateExplicit();
65+
// [END auth_cloud_explicit_adc]
66+
}
67+
68+
process.on('unhandledRejection', err => {
69+
console.error(err.message);
70+
process.exitCode = 1;
71+
});
72+
73+
main(...process.argv.slice(2));
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
// Copyright 2022 Google LLC
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
/**
16+
* Shows credentials auto-detections in the intercation with GCP libraries
17+
*
18+
* @param {string} projectId - Project ID or project number of the Cloud project you want to use.
19+
*/
20+
function main(projectId) {
21+
// [START auth_cloud_implicit_adc]
22+
/**
23+
* TODO(developer):
24+
* 1. Uncomment and replace these variables before running the sample.
25+
* 2. Set up ADC as described in https://cloud.google.com/docs/authentication/external/set-up-adc
26+
* 3. Make sure you have the necessary permission to list storage buckets "storage.buckets.list"
27+
* (https://cloud.google.com/storage/docs/access-control/iam-permissions#bucket_permissions)
28+
*/
29+
// const projectId = 'YOUR_PROJECT_ID';
30+
31+
const {Storage} = require('@google-cloud/storage');
32+
33+
async function authenticateImplicitWithAdc() {
34+
// This snippet demonstrates how to list buckets.
35+
// NOTE: Replace the client created below with the client required for your application.
36+
// Note that the credentials are not specified when constructing the client.
37+
// The client library finds your credentials using ADC.
38+
const storage = new Storage({
39+
projectId,
40+
});
41+
const [buckets] = await storage.getBuckets();
42+
console.log('Buckets:');
43+
44+
for (const bucket of buckets) {
45+
console.log(`- ${bucket.name}`);
46+
}
47+
48+
console.log('Listed all storage buckets.');
49+
}
50+
51+
authenticateImplicitWithAdc();
52+
// [END auth_cloud_implicit_adc]
53+
}
54+
55+
process.on('unhandledRejection', err => {
56+
console.error(err.message);
57+
process.exitCode = 1;
58+
});
59+
60+
main(...process.argv.slice(2));
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
// Copyright 2022 Google LLC
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
/**
16+
* Uses a service account (SA1) to impersonate as another service account (SA2) and obtain id token for the impersonated account.
17+
* To obtain token for SA2, SA1 should have the "roles/iam.serviceAccountTokenCreator" permission on SA2.
18+
*
19+
* @param {string} scope - The scope that you might need to request to access Google APIs,
20+
* depending on the level of access you need. For this example, we use the cloud-wide scope
21+
* and use IAM to narrow the permissions: https://cloud.google.com/docs/authentication#authorization_for_services.
22+
* For more information, see: https://developers.google.com/identity/protocols/oauth2/scopes.
23+
* @param {string} targetAudience - The service name for which the id token is requested. Service name refers to the
24+
* logical identifier of an API service, such as "http://www.example.com".
25+
* @param {string} impersonatedServiceAccount - The name of the privilege-bearing service account for whom
26+
* the credential is created.
27+
*/
28+
function main(scope, targetAudience, impersonatedServiceAccount) {
29+
// [START auth_cloud_idtoken_impersonated_credentials]
30+
/**
31+
* TODO(developer):
32+
* 1. Uncomment and replace these variables before running the sample.
33+
*/
34+
// const scope = 'https://www.googleapis.com/auth/cloud-platform';
35+
// const targetAudience = 'http://www.example.com';
36+
// const impersonatedServiceAccount = 'name@project.service.gserviceaccount.com';
37+
38+
const {GoogleAuth, Impersonated} = require('google-auth-library');
39+
40+
async function getIdTokenFromImpersonatedCredentials() {
41+
const googleAuth = new GoogleAuth();
42+
43+
// Construct the GoogleCredentials object which obtains the default configuration from your
44+
// working environment.
45+
const {credential} = await googleAuth.getApplicationDefault();
46+
47+
// delegates: The chained list of delegates required to grant the final accessToken.
48+
// For more information, see:
49+
// https://cloud.google.com/iam/docs/create-short-lived-credentials-direct#sa-credentials-permissions
50+
// Delegate is NOT USED here.
51+
const delegates = [];
52+
53+
// Create the impersonated credential.
54+
const impersonatedCredentials = new Impersonated({
55+
sourceClient: credential,
56+
delegates,
57+
targetPrincipal: impersonatedServiceAccount,
58+
targetScopes: [scope],
59+
lifetime: 300,
60+
});
61+
62+
// Get the ID token.
63+
// Once you've obtained the ID token, you can use it to make an authenticated call
64+
// to the target audience.
65+
await impersonatedCredentials.fetchIdToken(targetAudience, {
66+
includeEmail: true,
67+
});
68+
console.log('Generated ID token.');
69+
}
70+
71+
getIdTokenFromImpersonatedCredentials();
72+
// [END auth_cloud_idtoken_impersonated_credentials]
73+
}
74+
75+
process.on('unhandledRejection', err => {
76+
console.error(err.message);
77+
process.exitCode = 1;
78+
});
79+
80+
main(...process.argv.slice(2));

0 commit comments

Comments
 (0)