1
votes

I have a React + GraphQL application that reaches out to a Google Cloud Function to run some code. Currently I am allowing unauthenticated access, but I wish to lock it down. I am not seeing how I can authenticate like this in my React application:

fetch("https://REGION-PROJECT_ID.cloudfunctions.net/FUNCTION_NAME", {
     method: 'POST',
     headers: {
          'Content-Type': 'application/json',
          'Authorization': access_token //  <-------- this is what I want
     },
     body: JSON.stringify(something)
}) 

This example was stated in this thread: https://github.com/googleapis/google-auth-library-nodejs/issues/775

I would love to authenticate with a service account, but I don't want to have to use a Node server. Am I forced to go down the API key route?

This is the documentation for authenticating cloud functions:

https://cloud.google.com/functions/docs/securing/authenticating

Thanks!

2
You shouldn't authenticate with a service account from your web or mobile app. Giving up service account credentials to users of your app would be a massive security hole. You should instead using something like Firebase Authentication as end-user auth, then provide the end-user credentials to the function to be validated. - Doug Stevenson
I should have explained that I only mentioned the service account because my application will have/need credentials to reach out to the endpoint. I do not have end-users that need to authenticate. - ElektrikSpark
It's a security problem for your app (which is fully in the user's control) to receive a service account. That opens an attack vector for anyone who cares to reverse engineer your app. Just don't do it. - Doug Stevenson
If the users can access to your endpoint without being authenticated, don't secure your Functions (but be careful to the cost!). Else, if you have user authenticated, I should have a solution for you. - guillaume blaquiere

2 Answers

1
votes

I knew that there should have been a better solution for my use-case. API Gateway is new, so it was not coming up when I was looking for options. Thank you for the responses.

https://cloud.google.com/api-gateway/docs/quickstart

0
votes

It is not advised to use service account authentication from a web app. But if you would need to run this app locally for testing purposes, I would say you could use google-auth-library. More info and code examples can be found here.

You would also need the "Cloud Functions Invoker" role for the service account you are using.

Having said this, I would advise you to offload your authentication to a dedicated authentication provider like Firebase authentication, Auth0, or Okta.