Get hands-on experience with 20+ free Google Cloud products and $300 in free credit for new customers.

Cloud run uses secret

I am new to Google cloud. But here is what I want to accomplish.
I want to call a Cloud Function in a secure way. What are the steps in creating identity, secret and how to use it in sample next.js app invoking java cloud function.

1 1 1,280
1 REPLY 1

Hello @CookieKing02020  ,Welcome on Google Cloud Community.

  1. Creating Identity (Service Account):

    • Go to the Google Cloud Console.
    • Navigate to the IAM & Admin > Service Accounts section.
    • Click on "Create Service Account" and follow the prompts to create a new service account.
    • Assign the necessary roles/permissions to this service account depending on what actions it needs to perform (e.g., invoking Cloud Functions).
    • Once created, download the service account key file, which will be used to authenticate requests from your Next.js app.
  2. Creating Secrets:

    • Google Cloud provides various ways to manage secrets, one common method is using Secret Manager.
    • Navigate to the Secret Manager section in the Google Cloud Console.
    • Click on "Create Secret" and follow the prompts to create a new secret.
    • Add the necessary sensitive information such as API keys, database credentials, etc., to the secret.
    • Ensure the appropriate permissions are set to allow your service account (created earlier) to access this secret.
  3. Using Identity and Secrets in Next.js App:

    import { SecretManagerServiceClient } from '@google-cloud/secret-manager';
    import fetch from 'node-fetch';
    
    // Function to retrieve secret from Secret Manager
    async function getSecret(secretName) {
      const client = new SecretManagerServiceClient();
      const [version] = await client.accessSecretVersion({
        name: `projects/YOUR_PROJECT_ID/secrets/${secretName}/versions/latest`, // Replace YOUR_PROJECT_ID and secretName with actual values
      });
      const payload = version.payload.data.toString('utf8');
      return payload;
    }
    
    // Example usage within a Next.js API route
    export default async function handler(req, res) {
      try {
        // Retrieve secret from Secret Manager
        const mySecret = await getSecret('my-secret');
    
        // Do something with the secret
        console.log('My secret:', mySecret);
    
        // Make a request to your Java Cloud Function
        const functionUrl = 'https://REGION-PROJECT_ID.cloudfunctions.net/FUNCTION_NAME';
        const response = await fetch(functionUrl, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            // Add any additional headers if required
          },
          body: JSON.stringify({
            // Add any data you need to pass to your Cloud Function
            secret: mySecret,
            // Add any other parameters here
          }),
        });
    
        // Check if the request was successful
        if (response.ok) {
          // Handle the response from the Cloud Function
          const result = await response.json();
          console.log('Cloud Function response:', result);
          res.status(200).json(result);
        } else {
          console.error('Error invoking Cloud Function:', response.statusText);
          res.status(500).json({ error: 'Error invoking Cloud Function' });
        }
      } catch (error) {
        console.error('Error:', error.message);
        res.status(500).json({ error: 'Internal Server Error' });
      }
    }
    ​

Remember to replace 'YOUR_PROJECT_ID', 'my-secret', 'REGION-PROJECT_ID.cloudfunctions.net/FUNCTION_NAME', and any other placeholders with the actual values corresponding to your Google Cloud project, Secret Manager secret, and Java Cloud Function.

Save this code in a file under the pages/api/ directory in your Next.js app, and it will create an API route that retrieves a secret from Secret Manager and invokes your Java Cloud Function with that secret.

PS: Dunno if this code will work 😄 I've used gemini for generating this code as I'm not such an expert with JS 🙂 

Creating secret: https://cloud.google.com/secret-manager/docs/create-secret-quickstart#secretmanager-quickstart-gclou...

--
cheers,
DamianS
LinkedIn medium.com Cloudskillsboost