google-auth-library-nodejs
google-auth-library-nodejs copied to clipboard
feat(samples): auth samples
Thank you for opening a Pull Request! Before submitting your PR, there are a few things you can do to make sure it goes smoothly:
- [ ] Make sure to open an issue as a bug/issue before writing your code! That way we can discuss the change, evaluate designs, and agree on the general idea
- [ ] Ensure the tests and linter pass
- [ ] Code coverage does not decrease (if any source code was changed)
- [ ] Appropriate docs were updated (if necessary)
Fixes #<issue_number_goes_here> 🦕
Here is the summary of changes.
You are about to add 6 region tags.
-
samples/authenticateExplicit.js:19, tag
auth_cloud_explicit_adc
-
samples/authenticateImplicitWithAdc.js:21, tag
auth_cloud_implicit_adc
-
samples/idTokenFromImpersonatedCredentials.js:29, tag
auth_cloud_idtoken_impersonated_credentials
-
samples/idTokenFromMetadataServer.js:22, tag
auth_cloud_idtoken_metadata_server
-
samples/idTokenFromServiceAccount.js:23, tag
auth_cloud_idtoken_service_account
-
samples/verifyGoogleIdToken.js:27, tag
auth_cloud_verify_google_idtoken
This comment is generated by snippet-bot.
If you find problems with this result, please file an issue at:
https://github.com/googleapis/repo-automation-bots/issues.
To update this comment, add snippet-bot:force-run
label or use the checkbox below:
- [ ] Refresh this comment
Hi @piaxc @Sita04, thanks for the review, just sent the updates
Regarding moving comments for variables - unfortunately everywhere in js (and in Go) samples we have this structure, so user can jump directly to the github code if it is really needed. I moved important comments to the region tags, but for variables I prefer to keep the structure consistent with other languages.
@bcoe could you please help with reviewing this from node.js side?
Please use the /external/ links as currently written; they are used to allow for future updates of that documentation.
On Tue, Sep 13, 2022 at 7:58 PM Daniel Bankhead @.***> wrote:
@.**** requested changes on this pull request.
In samples/authenticateExplicit.js https://github.com/googleapis/google-auth-library-nodejs/pull/1444#discussion_r970249662 :
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+/**
- Lists storage buckets by authenticating with ADC.
*/
+function main() {
// [START auth_cloud_explicit_adc]
/**
- TODO(developer):
- Set up ADC as described in https://cloud.google.com/docs/authentication/external/set-up-adc
Should this link be https://cloud.google.com/docs/authentication/provide-credentials-adc? ⬇️ Suggested change
- Set up ADC as described in https://cloud.google.com/docs/authentication/external/set-up-adc
- Set up ADC as described in https://cloud.google.com/docs/authentication/provide-credentials-adc
In samples/authenticateExplicit.js https://github.com/googleapis/google-auth-library-nodejs/pull/1444#discussion_r970250765 :
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+/**
- Lists storage buckets by authenticating with ADC.
*/
+function main() {
// [START auth_cloud_explicit_adc]
/**
- TODO(developer):
- Set up ADC as described in https://cloud.google.com/docs/authentication/external/set-up-adc
- Make sure you have the necessary permission to list storage buckets "storage.buckets.list"
A link would help here. E.g. https://cloud.google.com/storage/docs/access-control/iam-permissions#bucket_permissions
In samples/authenticateExplicit.js https://github.com/googleapis/google-auth-library-nodejs/pull/1444#discussion_r970251970 :
const storageOptions = {
projectId,
authClient: credential,
};
// Construct the Storage client.
const storage = new Storage(storageOptions);
const [buckets] = await storage.getBuckets();
console.log('Buckets:');
for (const bucket of buckets) {
console.log(bucket.name);
}
console.log('Listed all storage buckets.');
I don't think this line is helpful outside of the test
In samples/authenticateExplicit.js https://github.com/googleapis/google-auth-library-nodejs/pull/1444#discussion_r970252481 :
- // const googleAuth = new GoogleAuth({ scopes: scope });
// For more information on scopes to use,
// see: https://developers.google.com/identity/protocols/oauth2/scopes
const storageOptions = {
projectId,
authClient: credential,
};
// Construct the Storage client.
const storage = new Storage(storageOptions);
const [buckets] = await storage.getBuckets();
console.log('Buckets:');
for (const bucket of buckets) {
console.log(bucket.name);
We can make the output easier to read. ⬇️ Suggested change
console.log(bucket.name);
console.log(`- ${bucket.name}`);
In samples/authenticateImplicitWithAdc.js https://github.com/googleapis/google-auth-library-nodejs/pull/1444#discussion_r970252944 :
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+/**
- Shows credentials auto-detections in the intercation with GCP libraries
- @param {string} projectId - Project ID or project number of the Cloud project you want to use.
*/
+function main(projectId) {
// [START auth_cloud_implicit_adc]
/**
- TODO(developer):
- Uncomment and replace these variables before running the sample.
- Set up ADC as described in https://cloud.google.com/docs/authentication/external/set-up-adc
⬇️ Suggested change
- Set up ADC as described in https://cloud.google.com/docs/authentication/external/set-up-adc
- Set up ADC as described in https://cloud.google.com/docs/authentication/provide-credentials-adc?
In samples/authenticateImplicitWithAdc.js https://github.com/googleapis/google-auth-library-nodejs/pull/1444#discussion_r970253106 :
+/**
- Shows credentials auto-detections in the intercation with GCP libraries
- @param {string} projectId - Project ID or project number of the Cloud project you want to use.
*/
+function main(projectId) {
// [START auth_cloud_implicit_adc]
/**
- TODO(developer):
- Uncomment and replace these variables before running the sample.
- Set up ADC as described in https://cloud.google.com/docs/authentication/external/set-up-adc
- Make sure that the user account or service account that you are using
- has the required permissions. For this sample, you must have "compute.instances.list".
*/
// const projectId = 'YOUR_PROJECT_ID';
// const zone = 'us-central1-a';
Unused ⬇️ Suggested change
- // const zone = 'us-central1-a';
In samples/authenticateImplicitWithAdc.js https://github.com/googleapis/google-auth-library-nodejs/pull/1444#discussion_r970253268 :
const {Storage} = @.***/storage');
async function authenticateImplicitWithAdc() {
// This snippet demonstrates how to list buckets.
// NOTE: Replace the client created below with the client required for your application.
// Note that the credentials are not specified when constructing the client.
// The client library finds your credentials using ADC.
const storage = new Storage({
projectId,
});
const [buckets] = await storage.getBuckets();
console.log('Buckets:');
for (const bucket of buckets) {
console.log(bucket.name);
⬇️ Suggested change
console.log(bucket.name);
console.log(`- ${bucket.name}`);
In samples/authenticateImplicitWithAdc.js https://github.com/googleapis/google-auth-library-nodejs/pull/1444#discussion_r970253341 :
- async function authenticateImplicitWithAdc() {
// This snippet demonstrates how to list buckets.
// NOTE: Replace the client created below with the client required for your application.
// Note that the credentials are not specified when constructing the client.
// The client library finds your credentials using ADC.
const storage = new Storage({
projectId,
});
const [buckets] = await storage.getBuckets();
console.log('Buckets:');
for (const bucket of buckets) {
console.log(bucket.name);
}
console.log('Listed all storage buckets.');
⬇️ Suggested change
- console.log('Listed all storage buckets.');
In samples/authenticateImplicitWithAdc.js https://github.com/googleapis/google-auth-library-nodejs/pull/1444#discussion_r970253433 :
- // NOTE: Replace the client created below with the client required for your application.
// Note that the credentials are not specified when constructing the client.
// The client library finds your credentials using ADC.
⬇️ Suggested change
// NOTE: Replace the client created below with the client required for your application.
// Note that the credentials are not specified when constructing the client.
// The client library finds your credentials using ADC.
In samples/authenticateImplicitWithAdc.js https://github.com/googleapis/google-auth-library-nodejs/pull/1444#discussion_r970253953 :
- Make sure that the user account or service account that you are using
- has the required permissions. For this sample, you must have "compute.instances.list".
Inaccurate line, should be something like Make sure you have the necessary permission to list storage buckets "storage.buckets.list" along with a helpful link https://cloud.google.com/storage/docs/access-control/iam-permissions#bucket_permissions
In samples/idTokenFromImpersonatedCredentials.js https://github.com/googleapis/google-auth-library-nodejs/pull/1444#discussion_r970254570 :
- // Create the impersonated credential.
const impersonatedCredentials = new Impersonated({
sourceClient: credential,
delegates,
targetPrincipal: impersonatedServiceAccount,
targetScopes: [scope],
lifetime: 300,
});
// Get the ID token.
// Once you've obtained the ID token, you can use it to make an authenticated call
// to the target audience.
await impersonatedCredentials.fetchIdToken(targetAudience, {
includeEmail: true,
});
console.log('Generated ID token.');
⬇️ Suggested change
- console.log('Generated ID token.');
In samples/idTokenFromImpersonatedCredentials.js https://github.com/googleapis/google-auth-library-nodejs/pull/1444#discussion_r970254923 :
- await impersonatedCredentials.fetchIdToken(targetAudience, {
includeEmail: true,
});
It would be helpful to do something with this result
In samples/idTokenFromImpersonatedCredentials.js https://github.com/googleapis/google-auth-library-nodejs/pull/1444#discussion_r970255715 :
- // delegates: The chained list of delegates required to grant the final accessToken.
// For more information, see:
// https://cloud.google.com/iam/docs/create-short-lived-credentials-direct#sa-credentials-permissions
// Delegate is NOT USED here.
const delegates = [];
Maybe leave this out since it's not used?
In samples/idTokenFromMetadataServer.js https://github.com/googleapis/google-auth-library-nodejs/pull/1444#discussion_r970256563 :
- await client.fetchIdToken(url);
- console.log('Generated ID token.');
It would be more helpful to do something with this token rather than to log this message
In samples/idTokenFromServiceAccount.js https://github.com/googleapis/google-auth-library-nodejs/pull/1444#discussion_r970257107 :
- // Get the ID token.
// Once you've obtained the ID token, use it to make an authenticated call
// to the target audience.
await client.fetchIdToken(targetAudience);
console.log('Generated ID token.');
It would be more helpful to do something with this token rather than to log this message
In samples/test/auth.test.js https://github.com/googleapis/google-auth-library-nodejs/pull/1444#discussion_r970258420 :
+const execSync = (cmd, opts) => {
- return cp.execSync(cmd, Object.assign({encoding: 'utf-8'}, opts));
+};
execFile or execFileSync would be cleaner rather than dealing with spacing, escaping, etc. (I'm assuming this was copied from tests from a few years back). See:
https://nodejs.org/api/child_process.html#child_processexecfilesyncfile-args-options
In samples/verifyGoogleIdToken.js https://github.com/googleapis/google-auth-library-nodejs/pull/1444#discussion_r970259190 :
- so verifying ID tokens before making Google API calls is usually unnecessary.
- @param {string} idToken - The Google ID token to verify.
- and use IAM to narrow the permissions: https://cloud.google.com/docs/authentication#authorization_for_services
- @param {string} expectedAudience - The service name for which the id token is requested. Service name refers to the
- logical identifier of an API service, such as "iap.googleapis.com".
*/
+function main(idToken, expectedAudience) {
// [START auth_cloud_verify_google_idtoken]
/**
- TODO(developer):
- Uncomment and replace these variables before running the sample.
*/
// const idToken = 'id-token';
// const targetAudience = 'pubsub.googleapis.com';
// const jwkUrk = 'https://www.googleapis.com/oauth2/v3/certs';
⬇️ Suggested change
- // const jwkUrk = 'https://www.googleapis.com/oauth2/v3/certs';
In samples/verifyGoogleIdToken.js https://github.com/googleapis/google-auth-library-nodejs/pull/1444#discussion_r970259826 :
- // Verify that the token contains subject and email claims.
// Get the User id.
if (result.payload['sub']) {
console.log(`User id: ${result.payload['sub']}`);
}
// Optionally, if "includeEmail" was set in the token options, check if the
// email was verified
if (result.payload['email_verified']) {
console.log(`Email verified: ${result.payload['email_verified']}`);
}
console.log('ID token verified.');
We could print this out: ⬇️ Suggested change
// Verify that the token contains subject and email claims.
// Get the User id.
if (result.payload['sub']) {
console.log(`User id: ${result.payload['sub']}`);
}
// Optionally, if "includeEmail" was set in the token options, check if the
// email was verified
if (result.payload['email_verified']) {
console.log(`Email verified: ${result.payload['email_verified']}`);
}
console.log('ID token verified.');
// The verified payload
console.dir(result.payload)
— Reply to this email directly, view it on GitHub https://github.com/googleapis/google-auth-library-nodejs/pull/1444#pullrequestreview-1106674901, or unsubscribe https://github.com/notifications/unsubscribe-auth/AEGJFRTRMOYCIH6EBAYOXJDV6E5LPANCNFSM57I32QIQ . You are receiving this because you were mentioned.Message ID: @.*** com>
--
Pia Chamberlain | Senior Technical Writer | she/her | Cloud Security Docs
@danielbankhead thanks a lot for the review! updated the PR
also we have already published canonical samples for Java (and Python): https://github.com/googleapis/google-auth-library-java/tree/main/samples/snippets/src/main/java, so most of the ideas and comments moved here (I commented)
I just moved the same code: https://github.com/GoogleCloudPlatform/nodejs-docs-samples/pull/2759 @danielbankhead could you please also approve? really appreciate
I just moved the same code: GoogleCloudPlatform/nodejs-docs-samples#2759 @danielbankhead could you please also approve? really appreciate
I like these here for integration purposes, say an unexpected breaking change was made in the codebase, having them here would make it easy to catch in a PR rather than in another repo. In either case, approved.
defer to @danielbankhead's review.