Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
298 views
in Technique[技术] by (71.8m points)

node.js - 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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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!)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...