Soumitri Pattnaik
Soumitri Pattnaik

Reputation: 3556

What is the best way to call an authenticated HTTP Cloud Function from Node JS app deployed in GCP?

We have an authenticated HTTP cloud function (CF). The endpoint for this CF is public but because it is authenticated, it requires a valid identity token (id_token) to be added to the Authorization header.

We have another Node JS application that is deployed in the same Google Cloud. What we want is to call the CF from the Node application, for which we will be needing a valid id token.

The GCP documentation for authentication is too generic and does not have anything for such kind of scenario.


So what is the best way to achieve this?

Note
Like every google Kubernetes deployment, the node application has a service account attached to it which already has cloud function invoker access.


Follow Up
Before posting the question here I had already followed the same approach as @guillaume mentioned in his answer. In my current code, I am hitting the metadata server from the Node JS application to get an id_token, and then I am sending the id_token in a header Authorization: 'Bearer [id_token]' to the CF HTTP request.

However, I am getting a 403 forbidden when I do that. I am not sure why?? enter image description here


I can verify the id_token fetched from the metadata server with the following endpoint.
https://www.googleapis.com/oauth2/v1/tokeninfo?id_token=[id_token]

It's a valid one. And it has the following fields.
Decoding the id_token in https://jwt.io/ shows the same field in the payload.

{
    "issued_to": "XXX",
    "audience": "[CLOUD_FUNTION_URL]",
    "user_id": "XXX",
    "expires_in": 3570,
    "issuer": "https://accounts.google.com",
    "issued_at": 1610010647
}

There is no service account email field!

Upvotes: 0

Views: 841

Answers (1)

guillaume blaquiere
guillaume blaquiere

Reputation: 75775

You have what you need in the documentation but I agree, it's not clear. It's named function-to-function authentication.

In fact, because the metadata server is deployed on each computes element on Google Cloud, you can reuse this solution everywhere (or almost everywhere! You can't generate an id_token on Cloud Build, I wrote an article and a workaround on this)

This article provides also a great workaround for local testing (because you don't have metadata server on your computer!)

Upvotes: 2

Related Questions