13

I'm trying to access the Google Cloud API from an AWS Lambda function but I don't know how to authenticate. The auth guide in the Google Cloud documentation (https://cloud.google.com/docs/authentication) wants me to download a credentials JSON file and use Application Default Credentials, but as anyone who has used hosted functions already knows, the point is that you don't need to manage a server or runtime environment, so Lambda doesn't give me the ability to store arbitrary files in the environment of the running code.

I can use the Cloud SDK locally to get an access token but it expires so I can't use it in my function as a permanent solution.

Is there not a way I can get an access token that I can use indefinitely in my code to call the Google Cloud API? Is there any other solution?

Mohamed Fakhreddine
  • 2,326
  • 2
  • 13
  • 10
  • What language you are programming in? What google api library you using? – cherba Jan 10 '17 at 13:50
  • My AWS Lamba function is written in Javascript on Node JS and I'm calling Google's Natural Language APIs. – Mohamed Fakhreddine Jan 10 '17 at 15:19
  • Have you tried https://github.com/google/google-auth-library-nodejs to manage credentials? – cherba Jan 10 '17 at 16:23
  • That library is an implementation of Application Default Credentials and still requires you to download the JSON credentials file, which I cannot do in the AWS Lambda function environment. – Mohamed Fakhreddine Jan 10 '17 at 17:15
  • Yes, I assume you would download that JSON key file, and embed its content in your code. You do not need to load it from a file, one can hardcode the credentials assuming your code is secure. – cherba Jan 10 '17 at 19:52
  • Thanks for the idea of hard-coding the content in the code. I kept digging and found the answer in an obscure link. I posted the answer below. – Mohamed Fakhreddine Jan 10 '17 at 21:37

1 Answers1

11

I found how to hard-code the credentials without the need to save them in a JSON file. It was in this documentation here:

https://googlecloudplatform.github.io/google-cloud-node/#/docs/language/0.7.0/guides/authentication

Below is an example that calls the Language API.

var language = require('@google-cloud/language')({
  projectId: '',
  credentials: {
      client_email: '',
      private_key: '',
  }
});

language.detectEntities('Axel Foley is from Detroit').then(function(data) {
  var entities = data[0];
  var apiResponse = data[1];
});
Mohamed Fakhreddine
  • 2,326
  • 2
  • 13
  • 10
  • 2
    Actually what worked for me was to add it to the ImageAnnoatorClient. Adding it to the require of vision said that "require is not a function": var vision = require('@google-cloud/vision'); // Creates a client const client = new vision.ImageAnnotatorClient({ projectId: config.projectId, credentials: { client_email: config.clientEmail, private_key: config.privateKey } }); – mortey Sep 25 '18 at 21:16