如何实现从一个GCloud函数向另一个发送带认证的GET请求?
解决GCloud函数HTTP端点认证调用问题
你已经配置了服务账号凭证和GOOGLE_APPLICATION_CREDENTIALS环境变量,只需借助Google官方认证库生成ID令牌并加入请求头,即可完成认证调用。具体步骤如下:
1. 安装依赖
在项目中安装Google认证库:
npm install google-auth-library
2. 修改调用代码
替换原有的https.get逻辑,加入认证令牌生成和请求头配置:
const https = require('https'); const { GoogleAuth } = require('google-auth-library'); async function callCloudFunction(endPoint, clientId, res) { const auth = new GoogleAuth(); // 目标受众为GCloud函数的基础端点URL(不含查询参数) const targetAudience = new URL(endPoint).origin + new URL(endPoint).pathname; try { // 获取ID令牌 const client = await auth.getIdTokenClient(targetAudience); const idToken = await client.idTokenProvider.fetchIdToken(targetAudience); // 配置请求选项,添加Authorization头 const options = { headers: { 'Authorization': `Bearer ${idToken}` } }; let data = ''; https.get(endPoint, options, (resp) => { resp.on('data', (chunk) => { data += chunk; }); resp.on('end', () => { console.log(JSON.parse(data).explanation); res.status(200).send(`SQL INSERTs have all been run for client(${clientId}) and they have been notified`); }); }).on("error", (err) => { console.log("Error: " + err.message); res.status(200).send(`There was an error running SQL INSERTs for client(${clientId}) and they have not been notified, error ${err.message}`); }); } catch (authErr) { console.log("Authentication error: " + authErr.message); res.status(500).send(`Failed to authenticate request for client(${clientId}), error ${authErr.message}`); } } // 根据业务逻辑触发调用 // callCloudFunction(yourEndPoint, yourClientId, yourResponseObject);
关键注意事项
- 权限配置:确保你的服务账号拥有
roles/cloudfunctions.invoker角色,否则即使令牌正确也会被拒绝访问。 - 目标受众:必须是函数端点的基础URL(如
https://us-central1-your-project.cloudfunctions.net/your-function),无需包含查询参数,参数可正常附加在endPoint中用于请求。 - 令牌缓存:
google-auth-library会自动缓存令牌,无需每次请求都重新生成,提升调用效率。
修改后即可解决你遇到的以下错误:
The request was not authenticated. Either allow unauthenticated invocations or set the proper Authorization header.
内容的提问来源于stack exchange,提问作者Rockwell Rice
相关产品推荐
相关产品推荐

