MCPcopy Create free account
hub / github.com/GoogleCloudPlatform/nodejs-docs-samples / tokenConsumer

Function tokenConsumer

auth/downscoping.js:88–127  ·  view source on GitHub ↗

* Simulates token consumer generating calling GCS APIs using generated * downscoped tokens for specified bucket. * * @param bucketName The name of the Cloud Storage bucket. * @param objectName The name of the object in the Cloud Storage bucket * to read.

(bucketName, objectName)

Source from the content-addressed store, hash-verified

86 * to read.
87 */
88 async function tokenConsumer(bucketName, objectName) {
89 // Create the OAuth credentials (the consumer).
90 const oauth2Client = new OAuth2Client();
91 // We are defining a refresh handler instead of a one-time access
92 // token/expiry pair.
93 // This will allow the consumer to obtain new downscoped tokens on
94 // demand every time a token is expired, without any additional code
95 // changes.
96 oauth2Client.refreshHandler = async () => {
97 // The common pattern of usage is to have a token broker pass the
98 // downscoped short-lived access tokens to a token consumer via some
99 // secure authenticated channel. For illustration purposes, we are
100 // generating the downscoped token locally. We want to test the ability
101 // to limit access to objects with a certain prefix string in the
102 // resource bucket. objectName.substring(0, 3) is the prefix here. This
103 // field is not required if access to all bucket resources are allowed.
104 // If access to limited resources in the bucket is needed, this mechanism
105 // can be used.
106 const refreshedAccessToken = await getTokenFromBroker(
107 bucketName,
108 objectName.substring(0, 3)
109 );
110 return {
111 access_token: refreshedAccessToken.token,
112 expiry_date: refreshedAccessToken.expirationTime,
113 };
114 };
115
116 const storageOptions = {
117 projectId: process.env.GOOGLE_CLOUD_PROJECT,
118 authClient: oauth2Client,
119 };
120
121 const storage = new Storage(storageOptions);
122 const downloadFile = await storage
123 .bucket(bucketName)
124 .file(objectName)
125 .download();
126 console.log(downloadFile.toString('utf8'));
127 }
128 // [END auth_downscoping_token_consumer]
129
130 try {

Calls 2

getTokenFromBrokerFunction · 0.85
toStringMethod · 0.80

Tested by

no test coverage detected