Skip to content
Merged
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
27 changes: 18 additions & 9 deletions run/authentication/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,19 +12,21 @@
// See the License for the specific language governing permissions and
// limitations under the License.

function main(receivingServiceURL = 'YOUR_RECEIVING_SERVICE_URL') {
// [START run_service_to_service_auth]
// Make sure to `npm install gcp-metadata` and `npm install got` or add the dependencies to your package.json

// Import the Metadata API
const gcpMetadata = require('gcp-metadata')
const got = require('got');

// TODO(developer): Add the URL of your receiving service
// const receivingServiceURL = 'YOUR_RECEIVING_SERVICE_URL''

const requestServiceToken = async () => {
try {

// Add the URL of your receiving service
const receivingServiceURL = ...

// Set up the metadata server request options
// See https://cloud.google.com/compute/docs/instances/verifying-instance-identity#request_signature

const metadataServerTokenPath = 'service-accounts/default/identity?audience=' + receivingServiceURL;
const tokenRequestOptions = {
headers: {
Expand All @@ -33,20 +35,27 @@ const requestServiceToken = async () => {
};

// Fetch the token and then provide it in the request to the receiving service
const tokenResponse = await gcpMetadata.instance(metadataServerTokenPath, tokenRequestOptions);
const token = await gcpMetadata.instance(metadataServerTokenPath, tokenRequestOptions);
const serviceRequestOptions = {
headers: {
'Authorization': 'bearer ' + tokenResponse
'Authorization': 'bearer ' + token

}
};

const serviceResponse = await got(receivingServiceURL, serviceRequestOptions);
res.send(serviceResponse.body);
return serviceResponse;

} catch (error) {
console.log('Metadata server could not respond to query ', error);
res.send(error);
return error;

}
};

// [END run_service_to_service_auth]

requestServiceToken();
};
main();

21 changes: 21 additions & 0 deletions run/authentication/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"name": "nodejs-auth",
"version": "1.0.0",
"description": "Cloud Run service-to-service authentication",
"main": "index.js",
"private": true,
"scripts": {
"start": "node index.js",
"test": "test"
},
"author": "krippaehne",
"license": "Apache-2.0",
"dependencies": {
"express": "^4.16.4",
"gcp-metadata": "^4.0.0",
"got": "^10.7.0"
},
"devDependencies": {
"mocha": "^7.0.0"
}
}