Home > Blockchain >  Making authenticated request to Google Cloud Function
Making authenticated request to Google Cloud Function

Time:05-17

I have Google Cloud Function which is acceble on https://us-central1-project.cloudfunctions.net/update Also I have Service Account with role 'Invoke Google Cloud Function'

First, I need to authenticate request, for this I'm using https://github.com/googleapis/google-auth-library-ruby

I've created google_cloud.json for my Service Account, I'm doing

credentials = Google::Auth::ServiceAccountJwtHeaderCredentials.make_creds({json_key_io: File.open('./config/google_cloud.json'), scope: 'https://www.googleapis.com/auth/
cloud-platform'})
headers = {}
credentials.apply(headers)

output looks like

{:authorization=>"Bearer ENCODED_TOKEN"} 

then I'm doing

curl -X POST -H "Authorization: Bearer ENCODED_TOKEN" -H 'Content-Type: application/json' -d '{"data":["user1"]}' "https://us-central1-project.cloudfunctions.net/update"

And it return HTML with

<h2>Your client does not have permission to the requested URL <code>/update_statuses</code>.</h2>

If I have a VPS server that should do API requests to Google Cloud Function, how should I authorize it?

CodePudding user response:

As mentioned by @DazWilkin, enable the service account by running gcloud auth print-identity-token then to get an identity token, you can gcloud auth print-identity-token --account=${ACCOUNT} where ACCOUNT is the email address of the service account.

You may refer to official documentation for more details.

CodePudding user response:

I've got it finally. Code in the question should be used to get Access Token, but for calling Google Cloud Functions I need ID Token. For that, instead of the scope we need to pass function url as target_audience

google_url = 'https://us-central1-project.cloudfunctions.net/update'
path = File.join(__dir__, '../config/google_cloud.json')
authorizer = Google::Auth::ServiceAccountCredentials.make_creds(json_key_io: File.open(path), target_audience: google_url)
token = authorizer.apply({})[:authorization]
  • Related