joegog
joegog

Reputation: 21

Accessing Google Cloud Function via API Key

I created a Google Cloud Function from my ML Models. It works fine with the google "Testing" on the GCP site of the function:

Screenshot of the testing

img_testing

I have the function hosted 2 times, one time with authentication (Google IAM) and a second time non-authenticated

authentication modi

img_auth

if I now want to invoke the function e.g. in postman the version without authentication works fine. But with authentication things it gets out of hand to figure out how to accomplish that.

How can I achieve access to the cloud function with an restricted API key?`

Upvotes: 2

Views: 6944

Answers (3)

Tonino
Tonino

Reputation: 1166

Recently Google added in beta a new Api Gateway, which will hide your google function declarations and provide an HTTP authentication using API KEY

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

Doing that, you can create an authentication between the client and the gateway using the API Key and the authentication between the gateway and the google function, can be done using a normal service account

Upvotes: 1

guillaume blaquiere
guillaume blaquiere

Reputation: 76073

You can't invoke your function directly with an API Key. You need to implement a proxy layer that check your API Key and perform a request with OAuth2 granted identity token. To achieve this, you can use Cloud Endpoint or its brand fresh serverless implementation API Gateway. I wrote an article on Cloud Endpoint and you can reuse it on API Gateway.

If it's just for Postman and your tests, you can generate a token with the GCLOUD CLI

gcloud auth print-identity-token

Copy the result and add it to the header of your request

Authorization: Bearer <token>

It is valid for 1H. Perform your tests, when it is expired, generate a new one and continue.

I also wrote a small tool for this. Perform a precall with Postman to get the token and then use it in your request as previously described

Upvotes: 3

Vikram Shinde
Vikram Shinde

Reputation: 1028

To make authenticated call to cloud function using postman, you need to jwt_token.

  1. First create service account
  2. Give Cloud function invoker access to this SA
  3. Generate JWT
import time
import google.auth.crypt
import google.auth.jwt

sa_keyfile = 'path_of_service_account'
iss = 'email_address_of_service_account'
aud = 'function_url'
iat = int(time.time())
exp = iat + 3600

def generate_jwt():
    """Generates a signed JSON Web Token using a Google API Service Account."""
    payload = {"iat": iat, "exp": exp, "iss": iss, "aud":  aud, "sub": iss, "email": iss}

    signer = google.auth.crypt.RSASigner.from_service_account_file(sa_keyfile)
    jwt = google.auth.jwt.encode(signer, payload)
    return jwt

if __name__ == '__main__':
    signed_jwt = generate_jwt()
    print(signed_jwt.decode()+'\n')

Upvotes: 0

Related Questions