0
votes

I'm following this: https://developer.chrome.com/apps/tut_oauth

But it doesn't work. When I invoke Cloud Function, I get 401 error. The Authorization: Bearer "access-token" is added in the request header. Although another question here[1] states that ID_TOKEN should be used. Which I tried via curl but have the same 401 error.

chrome.identity.getAuthToken({interactive: true}, function(token) {
        var dat = {
"user_email":email_id,
"user_id":user_id
};
     $.ajax({
        type: "POST",
        data:dat,
         dataType: 'json',
   url:str,
    contentType: "application/json",
         error: function (xhr, status, error) {
        console.log(xhr)
    }, success: function (data, status, xhr) {
        console.log('Success!' +data + status);
    },
      headers:{  
      'x-goog-project-id': 'xxxxxxxxxxxxx',
   'Authorization': 'Bearer ' + token,
   'Content-Type':'application/json',
   'Accept': 'application/json'
  }
    });
     });

[1] Why doesn't granting 'allAuthenticatedUsers' member the 'Cloud Functions Invoker' role work for google cloud functions?

2

2 Answers

0
votes

The tutorial that you mentioned used "access-token" to accesses a user's Google contacts using the Google People API and the Chrome Identity API.

If you want to access a Google Cloud Function which does not Allow unauthenticated invocations you have to use an ID_TOKEN.

For testing you can create a service account with --role="roles/cloudfunctions.invoker", then create a key.json file and export the GOOGLE_APPLICATION_CREDENTIALS env variable link

Finaly you can use:

curl "https://us-central1-your-project.cloudfunctions.net/yourfunction"
# Error 403 (Forbidden)
curl "https://us-central1-your-project.cloudfunctions.net/yourfunction"   -H "Authorization: bearer $(gcloud auth print-identity-token)"
#Success
0
votes

I gave up on this as there is no direct solution to invoke Cloud function using oauth in Chrome Apps. The alternative solution that worked is to authenticate via API key. That is using Cloud Function with Cloud Endpoints.

I followed the logic here: https://medium.com/@akash.mahale/triggering-google-cloud-functions-with-cloud-endpoints-and-api-key-857e94a8a3aa

But just need to take note that rotation of API keys should be done regularly and automatically..