Deploy
When you deploy cloud function, it shall ask
gcloud functions deploy FUNCTION_NAME
Allow unauthenticated invocations of new function [FUNCTION_NAME]?
(y/N)? N
NOTE: Select N
to restrict cloud functions from public/unauthenticated access.
Google Cloud Console - Cloud Functions
Access Google Cloud Console -> Cloud Functions
: https://console.cloud.google.com/functions/list
Check the FUNCTION NAME and the right panel will show up with PERMISSIONS
tab.
If you select Allow unauthenticated invocations = y
during deployment, there shall be a Cloud Functions Invoker
roles with Members = allUsers
.
NOTE: If you want to prevent unauthenticated access, delete allUsers
from Cloud Functions Invoker
.
If you select Allow unauthenticated invocations = N
during deployment, there might not be aCloud Functions Invoker
roles at PERMISSIONS
tab.
NOTE: Sometimes you might see NAME@PROJECT_ID.iam.gserviceaccount.com
with inherited
attribute under Cloud Functions Invoker
if you have a Service Accounts
with the IAM Role Cloud Functions Invoker
.
Try access the cloud functions (e.g. https://us-central1-PROJECT_ID.cloudfunctions.net/FUNCTION_NAME
) and you should get the following message.
Error: Forbidden
Your client does not have permission to get URL /FUNCTION_NAME from this server.
Create Service Account
Access Google Cloud Console -> Service accounts
: https://console.cloud.google.com/iam-admin/serviceaccounts
Click + Create Service Account
- Service account name:
cloud-functions-invoker
- Description:
Click Create
At Grant this service account access to project (optional)
, assign the role Cloud Functions Invoker
.
At Grant users access to this service account (optional)
, leave it as it is.
NOTE: Technically, this new service account cloud-functions-invoker@PROJECT_ID.iam.gserviceaccount.com
should appear at Cloud Functions PERMISSIONS
tab under Cloud Functions Invoker
with inherited
attribute. Sometimes the Web UI might not update properly or in-time.
Cloud Scheduler
Access Google Cloud Console -> Cloud Scheduler
: https://console.cloud.google.com/cloudscheduler
Click Create Job
- Name:
test_cloud_functions_authrization
- Description:
- Frequency:
0 9 * * 1
(Every Monday 9AM), more example. - Time zone
- Target:
HTTP
- URL: https://us-central1-PROJECT_ID.cloudfunctions.net/FUNCTION_NAME
- HTTP method:
POST
orGET
Click show more
- Auth header:
Add OIDC account
- Service account:
cloud-functions-invoker@PROJECT_ID.iam.gserviceaccount.com
- Audience: If you leave if BLACK, it will copy from URL
NOTE: If you use query parameter for URL (e.g. https://us-central1-PROJECT_ID.cloudfunctions.net/FUNCTION_NAME?name=hello
, for Audience
you must use https://us-central1-PROJECT_ID.cloudfunctions.net/FUNCTION_NAME
without query parameter, else authorization will fail).
After created the job, you can click Run Now
to test if the authentication work as expected.
References: