API Key Authentication with Google Cloud API Gateway and Cloud Run Posted on February 10, 2024February 15, 2024 By Justin Table of Contents Toggle IntroductionWARNINGBasic StepsPrerequisitesGoogle Cloud SetupEnable Needed Google Cloud ServicesConsole MethodCommand Line MethodCreate a Google Cloud Service AccountConsole MethodCommand Line MethodBackend API CreationCreate a simple Python-based APImain.pyrequirements.txtDockerfilestart.shDeploy Code as a Docker Container to Cloud RunTestingReenable AuthenticationGrant Service Account PermissionsAPI Gateway SetupCreate API Gateway APITesting Your APICloud Run URLAPI Gateway URLGET TestsPOST TestsConclusion Deploy Code as a Docker Container to Cloud Run Now that we have our code ready, we can actually deploy it to Google Cloud Run and expose our endpoints to the world. If you have the Google Cloud Code extension installed in VS Code, the process is very easy. Click the Cloud Code icon on the left sidebar: Expand CLOUD RUN Click Login to Google Cloud (if necessary) and follow the browser prompts Click Select a project Choose the appropriate Google Cloud Project (the one you enabled the various services on earlier) Click the Deploy to Cloud Run button: Wait… and wait… Don’t worry if you see this screen for several minutes the first time you try this (you may see it installing various Cloud SDK components down in the bottom status bar): Select the appropriate options for your deployment. In my case, I’m choosing: Service: Create a service Service name: api-gateway-demo Region: us-central1 (Iowa) Authentication: Allow unauthenticated invocations This is a temporary setting, just to confirm that the API we deployed is working. Remember to switch this setting later! Container image URL: gcr.io/api-gateway-key-auth-demo/api-gateway-demo Service account: (blank) This is the service account that Cloud Run will use (like if your API needed to interact with Cloud Storage or another GCP API), not that our API Gateway will use. Leaving this blank tells Cloud Run to use whatever the default Cloud Run service account is in your environment. Build environment: Local Builder: Docker Docker: Dockerfile Click Deploy This process will take several minutes, during which you should see your Docker image actually getting built and deployed to Cloud Run. When it’s through, the output should show the URL for your new Cloud Run service: Testing Because we set up our Cloud Run service to allow unauthenticated invocations, we can easily test the GET endpoint just by browsing to it: Testing the POST endpoint takes a little more effort. Because our browser sends a GET request and we defined the endpoint for the POST method, we’ll get a “Method Not Allowed” response if we just try to browse to it: For this kind of testing, I like to use the curl command line tool. On a Windows machine with Git installed, you can open the Git Bash application and just type out the request in the command line. For example, given my example URL of https://api-gateway-demo-6j4xxtorma-uc.a.run.app, my POST command to add 10 and 35 would look like this: curl -X POST -H "Content-Type: application/json" https://api-gateway-demo-6j4xxtorma-uc.a.run.app/post/add -d '{"num1": 10, "num2": 35}' And if everything’s working properly, I should get a response like this: Reenable Authentication Before moving on to the next section, make sure to shut off public access to your Cloud Run job. The easiest way is through the GCP console. Browse to https://console.cloud.google.com/run and click on your Cloud Run service Click the Security link at the top navigation bar. Select “Require authentication” in the Authentication panel. Click Save It may take a few minutes before the change takes effect. Use the steps in the above Testing section to confirm. Grant Service Account Permissions Earlier in the tutorial, we created an example service account called “api-gateway-demo-service-accou” to use for this process (see the Create a Google Cloud Service Account section), and we can find its associated email address using (surprise!) gcloud: gcloud iam service-accounts list --project={{PROJECT_ID}} This account needs to have the Cloud Run Invoker role (roles/run.invoker) on either the project where the Cloud Run service is deployed or just on the specific Cloud Run service (my preference). To add that role to the service account: gcloud run services add-iam-policy-binding {{CLOUD_RUN_SERVICE_NAME}} \ --region='{{GCP_REGION}}' --member='serviceAccount:{{SERVICE_ACCOUNT_EMAIL}}' \ --role='roles/run.invoker' --project={{PROJECT_ID}} Where: {{CLOUD_RUN_SERVICE_NAME}}: Name of our backend Cloud Run service (e.g. api-gateway-demo). {{GCP_REGION}}: The region where our Cloud Run service was deployed (e.g. us-central1). {{SERVICE_ACCOUNT_EMAIL}}: The email address of the service account to which we want to grant the Cloud Run Invoker role (e.g. api-gateway-demo-service-accou@api-gateway-key-auth-demo.iam.gserviceaccount.com) {{PROJECT_ID}}: Name of the Google Cloud project you’re using for the tutorial (e.g. api-gateway-key-auth-demo) You should see a result similar to this: Pages: 1 2 3 4 5 6 7 8 9 10 11 12 Backend Stuff APICloud RunGCPPythonTutorial